Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
In an interview I was asked this questions that how can we create an object of static clsss while I have read on everwhere that we can't create object of static class? Please guide if can create then how ?
Posted
Comments
BillWoodruff 3-Sep-12 22:38pm    
Need more clarification here: are you talking about creating a static object or class at run-time ? Or ?

MSDN:
A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword.


Check Static Classes and Static Class Members (C# Programming Guide)[^].

Moreover:
Quote:

They only contain static members.
They cannot be instantiated.
They are sealed.
They cannot contain Instance Constructors (C# Programming Guide).



--Amit
 
Share this answer
 
Comments
Prasad_Kulkarni 4-Sep-12 7:54am    
Good one +5
_Amy 4-Sep-12 8:10am    
Thanks Prasad. :)
Member 14144075 28-Feb-19 9:52am    
nice bruhhh
Member 14144075 28-Feb-19 9:52am    
niceee
Hemant__Sharma 5-Feb-14 2:55am    
To the point, crisp and clear +4
Yes we can create object for static classes. But it really does not make sense and is not required.

For eg:

C#
class Sample
{
    public static void main(String args[])
    {
        Math m=new Math();
        System.out.println(m.sqrt(120)); //with help of object
        System.out.println(Math.sqrt(120)); //with out object
    }
}
 
Share this answer
 
Comments
Mohamed Mitwalli 3-Sep-12 14:37pm    
5+
Manas Bhardwaj 3-Sep-12 14:39pm    
thx!
[no name] 3-Sep-12 14:41pm    
can you please elaborate!
Zoltán Zörgő 3-Sep-12 16:11pm    
Sorry, but this is no C# code, it is Java. And by the way, in C# Math m = new Math(); won't compile.
Manas Bhardwaj 4-Sep-12 3:36am    
My bad. Had my eclipse IDE open and didn't really focus on C# tag :(
Listen first, If we see the difference between a non-static and a static class in C# is simply that a static class cannot be instantiated. This means that you don’t use the new keyword to instantiate an instance of the class. Instead, you will access members of the static class by using the class name. Basically, a static class is intended to be a container for a set of methods that only work with supplied parameters and don’t have a need to store or retrieve data that is unique to them. An example of a static class that’s built into the .NET Framework is the System.Math class. It contains methods which perform various mathematical operations.

A static class is like a regular class that only has static members and has a private constructor. If you have a class like this in your design it’s best to make it a static class in order to use the features in the compiler which will insure that instances of the class cannot be created or inherited. By taking this step it will make your code more solid.

Sometimes there is confusion between a static class and a singleton class where only one instance is allowed. The way to separate them is to understand that the static class should not have any internal variables, each method should function independently, like a function library. However, a singleton class may expose internal values as properties and allow the storage and retrieval of these values.

As I mentioned above static classes cannot be instantiated. Instead, the Framework will call the private constructor for the static class prior to the first place the class is referenced in code. This allows you to blend in your function library seamlessly into your program so if you had a static class like this…
public static class MyFunctions
{
public static string Test1(string myValue)
{
// Code
}

public static int Test2(int myValue)
{
// Code
}
}

…you can call it like so…
MyFunctions.Test1(CurrentValue);
…without having to create an instance of the object using the new keyword (which you can’t do with a static class anyway). Also, a static class will remain in memory for the lifetime of the application domain where it is created.

As you can see in the example above, a static class can only contain static members. The program won’t compile if you don’t remember to mark each of them as static. Also, static classes are sealed, which means that they cannot be inherited and cannot inherit from any class other than System.Object. While a static class cannot have an instance constructor, they can have a private, static, constructor. This routine will be called when the Framework creates the instance of the object.

One thing to bear in mind here is that if your static class requires a lot of extensive initialization it may not be a good candidate for a static class. In my view, these classes are intended for groups of related, but essentially standalone, functions. Having a substantial initialization routine may indicate that the class might work better as a singleton class or as a regular class. Taking this into consideration early on can prevent you from having to recode a static class into something else.
 
Share this answer
 
Comments
madhuri@mumbai 4-Sep-12 2:30am    
thats great,
above all answers very knowledible for static class information,
thanks all of you...
Aadhar Joshi 13-Sep-12 5:02am    
you are welcome and your questions are also welcome..!!
Prasad_Kulkarni 4-Sep-12 7:55am    
Good work +5
Aadhar Joshi 13-Sep-12 5:03am    
thanks
Ganesh Nikam 12-Sep-12 5:05am    
gra8
Add a static class to some new solution:
C#
namespace TestStatic
{
    public static class StaticClass
    {
        public static int staticInt = 0;
    }
}
From some button press in some container, try the following:
C#
private void button1_Click(object sender, EventArgs e)
{

    // uncomment this line before you click the button
    // a second time
    //int x = StaticClass.staticInt;

    MessageBox.Show(typeof(StaticClass).ToString());

    MessageBox.Show((typeof(StaticClass) is Object).ToString());
}
Observe the results.

So, a static class is a Type, and an object ! For extra points explain why you cannot use 'GetType() here instead of 'typeof(), and explain why you cannot directly code:
C#
MessageBox.Show((StaticClass is Object).ToString());
:)

best, Bill
 
Share this answer
 
Hey See below link:
It will helpful for you.
Why Staic Class?[^]
 
Share this answer
 
Quote:
It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

Ref: http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.80).aspx

The main features of a static class are:

1) They only contain static members.
2) They cannot be instantiated.
3) They are sealed.
4) They cannot contain Instance Constructors (C# Programming Guide).

Read the above link. That provides you sufficient information about Static class.

You said that, "In an interview I was asked this questions that how can we create an object of static class"? Answer was straightforward.. "Not possible(in C#)"
 
Share this answer
 
static blocks and static classes are executed before constructor execution but object can be created while executing the constructor only but static blocks are executed before executing constructor so we can't create an object on static classes.
 
Share this answer
 
Hi,

First of all one thing you should keep in your mind that Static class/Static method have only single instance per application.

When very first time you call any of the method from your static class, at that time it's Instance will be created. So if you have 100 Static class in your application it's instance will not be created until it's Method call. If you call two method of your Static class Instance will be created for only first method call and for second method call the lastly created instance will be used.

Hope you got the idea
Best luck
Thanks
-Amit Gajjar
 
Share this answer
 
hi this vijaypratapsingh .answer of your question



A static class cannot be instantiated. You cannot, at any time write new MyStaticClass() without the compiler complaining. It never has a this reference, and the fields, properties and methods can only ever be accessed via the class name: MyStaticClass.MyMethod() In addition, you cannot derive from a static class, not can a static class derive from any class other than object
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900