Can anyone explain how the CLR handles Static classes? Does the CLR create one singleton instance for handling static classes internally? If not, why do we have a static constructor in C#? (Per my understanding, we use constructors only for instantiating the class)
First of all there is no static class in CLR. CLR doesn't know anything about static class.
It is the feature of C#.
Static classes are compiled into abstract as well as sealed class. Making it abstract prevent instantiation of it and sealed prevents inheritance.
Static classes are no special, it is just a simple class with all members static.
Is, CLR internally creates one singleton instance for handling static
classes?
No, it is abstract and can't be instantiated.
If not why we have an static constructor in C#?
Static constructor will be called when type is first referenced or instantiated. It is used to initialize the static members of the class.
When is a static constructor called in C#?
The static constructor is called when the type is first referenced. It doesn't have to be a static class to have a static constructor.
The CLR doesn't create a singleton instance of a static class. It does keep the static variables in memory though after they are initialized.
Related
Hello All:
what is difference making full class static and making functions of the class as static?
I mean are there any performance issues?
The feature of static classes was only introduced in C# 2. The CLR doesn't really have such a concept. A static class in C#:
Has no constructors, not even a default parameterless one
Is sealed: it can't be subclassed
Is abstract: you can't create instances of it (which also follows from there being no constructors)
Can only contain static members
Can't be used as a parameter or variable type or a generic type argument etc.
Can't specify any base type other than object
There's no performance difference between using static members of a "normal" class and using ones in a static class. It's primarily a way of stating the intention that there should never be any instances of this class, without having to provide a private and never-called constructor, and forcing the compiler to check that you're not trying to use it as a normal class.
Note that extension methods (introduced in C# 3) can only be declared in a top-level, non-generic static class.
It has two implications:
All methods of the class must also be static.
You can't make an instance of that class other places in your code.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
When to Use Static Classes in C#
why anyone would write a static class. we can declare a static method in any class and just call that method without creating class instance. so please tell me in what type of situation a person would create a static class and also tell me what are the main differences between static class and normal class.
thanks
A static class cannot be instantiated. It's main uses are to make it clear that the class has no instance methods and to prevent people from accidentally trying to "new" the class.
Generally I would advise you not to write static classes.
There are cases where you want them though
Extension methods have to live on static classes. This is the best reason to have a static class.
If you do have a bunch of static methods that don't make sense as extension methods and don't fit into your object model then there might be room for a collection of static methods. This is particularly the case when you cannot redesign your app.
Sometimes this happens because you are dealing with some 3rd party stuff that you cannot change. Then if you end up with a class with only static methods on it - you should make it static since anyone creating an instance is clearly not understanding what you have done.
Having said all of that for the most part my advices is avoid static methods, classes and data. I am not saying never use them - just try not to.
A static class cannot contain any constructors, only a static constructor that is called first time one of its members is accessed.
That is basically the difference. Performance wise we also get another for free by the compiler since it can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.
Static classes are also sealed and therefore cannot be inherited.
http://msdn.microsoft.com/en-us/library/79b3xss3(v=VS.100).aspx
A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type.
Another valid point is that Extension Methods has to be declared in a static class
http://en.wikipedia.org/wiki/Extension_method
The new language feature of extension methods in C# 3.0, however, makes the latter code possible. This approach requires a static class and a static method.
In static class all method all static. we can not declare normal method in static class.
differences between static class and normal class.
We can not create object of static class, when we use method of static class just use classname.MethodName but in normal class we have to first create object of class then we can access method of normal class.
static class ex.
Class1.functionname();
normal class ex.
Class1 cs = new class1();
cs.functionname();
functionname should not be private.
The difference is that you can't instantiate a static class. So you'd make a class static if you don't want it ever being instantiated. This is useful in cases when you're dealing with threading issues, and you want all threads to be guaranteed to use the same instance of your class.
A more philosophical scenario is when you have a class that doesn't need to be instantiated, such as (for example) you're building a database application and you create one class to do all the database access stuff. It's basically just a collection of methods. Then making the class static simply becomes a step to make your design more consistent.
I was asked the above question in an interview. Could you please explain the differences? ( performance - memory - usage - when to use which ? )
Thank you,
Erkan
Declaring a static class documents your intent for that class to be a collection of static functionality, and anyone adding instance members will get a compilation error.
A non-static class with static members usually indicates that the class is designed to be instantiated at some point. Static methods of these classes usually do one of two things:
Provide a factory method for creating an instance of that type;
Provide helper functionality that does not require an instance of the type;
Also, as mentioned already, extension methods can only be declared on a static class.
I assume you were asked for the differences?
A static method on a static class can be used to define an extension method. A static method on a non-static class cannot.
In terms of performance and memory usage; precisely nothing. Having a static class means you know there are no instances, but back in 1.1 having a private constructor sufficed. Use a static class if it simply makes no sense to have an instance! (utility classes etc)
When you are providing utility functions and all your methods are static, I recommend you use static methods in a static class.
When you want to provide utility methods that just deal with your instance, I recommend you use static methods in a non-static class. For example:
var myClass = MyClass.Create();
var myClass = MyClass.Parse("serialized.MyClass");
In terms of memory, there is a slight difference: the static method in a non-static class will be allocated only when the first instance of that type is created, and deallocated when the last instance of that type is deallocated. Static methods on instance objects are very useful when we have collections of objects of the same type in order to decrease the amount of memory used. The drawback of using static methods is that they are not unit testable, so before creating a static method, an eye should be kept on how it will affect the code coverage.
One major difference I faced when deciding whether to go with normal class with all static methods or, use a static class, is that a normal class supports interface implementation, where as static class does not.
I use static class only when I am sure it will be a collection of static functions (usually helper functions), and will never be in the main stream of program. I promote interface programming, for dependency injections, unit testing etc. So, for main flow of program, I use normal class with static methods.
Ref: MS Docs
In C# what is the difference between:
public static class ClassName {}
And:
public class ClassName {}
Firstly, a comment on an answer asked about what "static" means. In C# terms, "static" means "relating to the type itself, rather than an instance of the type." You access a static member (from another type) using the type name instead of a reference or a value. For example:
// Static method, so called using type name
Guid someGuid = Guid.NewGuid();
// Instance method, called on a value
string asString = someGuid.ToString();
Now, static classes...
Static classes are usually used as "utility" classes. The canonical example is probably System.Math. It doesn't make sense to create an instance of math - it just "is". A few rules (both "can" and "can't"):
Static classes always derive from object. You can't specify a different base type, or make the static class implement an interface.
Static classes can't have any instance members - all variables, methods etc must be static.
Static classes can't declare any instance constructors and the compiler doesn't create a parameterless constructor by default. (Before static classes came in C# 2.0, people would often create an abstract class with a private constructor, which prevented instantiation. No need here.)
Static classes are implicitly abstract (i.e. they're compiled to IL which describes an abstract class) but you can't add the abstract modifier yourself.
Static classes are implicitly sealed (i.e. they're compiled to IL which describes an sealed class) but you can't add the sealed modifier yourself.
Static classes may be generic.
Static classes may be nested, in either non-static or static classes.
Static classes may have nested types, either non-static or static.
Only static, top-level non-generic classes can contain extension methods (C# 3.0).
A static class cannot be instantiated, and can contain only static members. Hence, the calls for a static class are as: MyStaticClass.MyMethod(...) or MyStaticClass.MyConstant.
A non static class can be instantiated and may contain non-static members (instance constructors, destructor, indexers). A non-static member of a non-static class is callable only through an object:
MyNonStaticClass x = new MyNonStaticClass(...);
x.MyNonStaticMethod(...);
public static class ClassName {}
A static class is just like a global variable: you can use it anywhere in your code without instantiating them.
For example: ClassName. After the dot operator, you can use any property or function of it.
public class ClassName {}
But if you have non-static class then you need to create an instance of this class.
For example:
ClassName classNameObject = new ClassName();
A static class also can not be inherited from, whereas a non-static class with static members can be inherited from.
All methods/properties in a static class must be static, whereas a 'normal' class can contain a mix of instance and static methods.
You can't instantiate (create objects of) a static class. And it can only contain static members.
Example: System.Math
Static class can contain static members only.
Static member can be used without instantiating a class first.
Static classes and members are used to create data and methods that can be accessed without creating an instance (using the new keyword, they cannot have a constructor) of the class.
Static classes can be declared when there is no dependence on the its own object identity, so a static class must contain only static members.
This classes are loaded by the CLR when the program or namespace containing the class is loaded.
They are also sealed, cannot be inherited from.
http://www.javaworld.com/javaworld/javaqa/1999-08/01-qa-static2.html - very good article on this. This is for Java. But i think concept should should same in C# too.
Static variable in c
a variable local to a class as auto variables
but static variable do not disappear as function is no longer active.Their values persist.If control comes back,static variables have same value
static function in c
functions that are not visible to functions in other files.
*static data members in cpp *
data members can be variables or functions in cpp
static applies to both data members
the class itself can be static
"There is only one copy of static data memberss shared by all objects in that class"
static data members can access only static data members
static class
this class cannot instantiate objects
Most importantly, "A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides." - From Microsoft
I have several classes that do not really need any state. From the organizational point of view, I would like to put them into hierarchy.
But it seems I can't declare inheritance for static classes.
Something like that:
public static class Base
{
}
public static class Inherited : Base
{
}
will not work.
Why have the designers of the language closed that possibility?
Citation from here:
This is actually by design. There seems to be no good reason to inherit a static class. It has public static members that you can always access via the class name itself. The only reasons I have seen for inheriting static stuff have been bad ones, such as saving a couple of characters of typing.
There may be reason to consider mechanisms to bring static members directly into scope (and we will in fact consider this after the Orcas product cycle), but static class inheritance is not the way to go: It is the wrong mechanism to use, and works only for static members that happen to reside in a static class.
(Mads Torgersen, C# Language PM)
Other opinions from channel9
Inheritance in .NET works only on instance base. Static methods are defined on the type level not on the instance level. That is why overriding doesn't work with static methods/properties/events...
Static methods are only held once in memory. There is no virtual table etc. that is created for them.
If you invoke an instance method in .NET, you always give it the current instance. This is hidden by the .NET runtime, but it happens. Each instance method has as first argument a pointer (reference) to the object that the method is run on. This doesn't happen with static methods (as they are defined on type level). How should the compiler decide to select the method to invoke?
(littleguru)
And as a valuable idea, littleguru has a partial "workaround" for this issue: the Singleton pattern.
The main reason that you cannot inherit a static class is that they are abstract and sealed (this also prevents any instance of them from being created).
So this:
static class Foo { }
compiles to this IL:
.class private abstract auto ansi sealed beforefieldinit Foo
extends [mscorlib]System.Object
{
}
Think about it this way: you access static members via type name, like this:
MyStaticType.MyStaticMember();
Were you to inherit from that class, you would have to access it via the new type name:
MyNewType.MyStaticMember();
Thus, the new item bears no relationships to the original when used in code. There would be no way to take advantage of any inheritance relationship for things like polymorphism.
Perhaps you're thinking you just want to extend some of the items in the original class. In that case, there's nothing preventing you from just using a member of the original in an entirely new type.
Perhaps you want to add methods to an existing static type. You can do that already via extension methods.
Perhaps you want to be able to pass a static Type to a function at runtime and call a method on that type, without knowing exactly what the method does. In that case, you can use an Interface.
So, in the end you don't really gain anything from inheriting static classes.
Hmmm... would it be much different if you just had non-static classes filled with static methods..?
What you want to achieve by using class hierarchy can be achieved merely through namespacing. So languages that support namespapces ( like C#) will have no use of implementing class hierarchy of static classes. Since you can not instantiate any of the classes, all you need is a hierarchical organization of class definitions which you can obtain through the use of namespaces
You can use composition instead... this will allow you to access class objects from the static type. But still cant implements interfaces or abstract classes
Although you can access "inherited" static members through the inherited classes name, static members are not really inherited. This is in part why they can't be virtual or abstract and can't be overridden. In your example, if you declared a Base.Method(), the compiler will map a call to Inherited.Method() back to Base.Method() anyway. You might as well call Base.Method() explicitly. You can write a small test and see the result with Reflector.
So... if you can't inherit static members, and if static classes can contain only static members, what good would inheriting a static class do?
A workaround you can do is not use static classes but hide the constructor so the classes static members are the only thing accessible outside the class. The result is an inheritable "static" class essentially:
public class TestClass<T>
{
protected TestClass()
{ }
public static T Add(T x, T y)
{
return (dynamic)x + (dynamic)y;
}
}
public class TestClass : TestClass<double>
{
// Inherited classes will also need to have protected constructors to prevent people from creating instances of them.
protected TestClass()
{ }
}
TestClass.Add(3.0, 4.0)
TestClass<int>.Add(3, 4)
// Creating a class instance is not allowed because the constructors are inaccessible.
// new TestClass();
// new TestClass<int>();
Unfortunately because of the "by-design" language limitation we can't do:
public static class TestClass<T>
{
public static T Add(T x, T y)
{
return (dynamic)x + (dynamic)y;
}
}
public static class TestClass : TestClass<double>
{
}
You can do something that will look like static inheritance.
Here is the trick:
public abstract class StaticBase<TSuccessor>
where TSuccessor : StaticBase<TSuccessor>, new()
{
protected static readonly TSuccessor Instance = new TSuccessor();
}
Then you can do this:
public class Base : StaticBase<Base>
{
public Base()
{
}
public void MethodA()
{
}
}
public class Inherited : Base
{
private Inherited()
{
}
public new static void MethodA()
{
Instance.MethodA();
}
}
The Inherited class is not static itself, but we don't allow to create it. It actually has inherited static constructor which builds Base, and all properties and methods of Base available as static. Now the only thing left to do make static wrappers for each method and property you need to expose to your static context.
There are downsides like the need for manual creation of static wrapper methods and new keyword. But this approach helps support something that is really similar to static inheritance.
P.S.
We used this for creating compiled queries, and this actually can be replaced with ConcurrentDictionary, but a static read-only field with its thread safety was good enough.
My answer: poor design choice. ;-)
This is an interesting debate focused on syntax impact. The core of the argument, in my view, is that a design decision led to sealed static classes. A focus on transparency of the static class's names appearing at the top level instead of hiding ('confusing') behind child names? One can image a language implementation that could access the base or the child directly, confusing.
A pseudo example, assuming static inheritance was defined in some way.
public static class MyStaticBase
{
SomeType AttributeBase;
}
public static class MyStaticChild : MyStaticBase
{
SomeType AttributeChild;
}
would lead to:
// ...
DoSomethingTo(MyStaticBase.AttributeBase);
// ...
which could (would?) impact the same storage as
// ...
DoSomethingTo(MyStaticChild.AttributeBase);
// ...
Very confusing!
But wait! How would the compiler deal with MyStaticBase and MyStaticChild having the same signature defined in both? If the child overrides than my above example would NOT change the same storage, maybe? This leads to even more confusion.
I believe there is a strong informational space justification for limited static inheritance. More on the limits shortly. This pseudocode shows the value:
public static class MyStaticBase<T>
{
public static T Payload;
public static void Load(StorageSpecs);
public static void Save(StorageSpecs);
public static SomeType AttributeBase
public static SomeType MethodBase(){/*...*/};
}
Then you get:
public static class MyStaticChild : MyStaticBase<MyChildPlayloadType>
{
public static SomeType AttributeChild;
public static SomeType SomeChildMethod(){/*...*/};
// No need to create the PlayLoad, Load(), and Save().
// You, 'should' be prevented from creating them, more on this in a sec...
}
Usage looks like:
// ...
MyStaticChild.Load(FileNamePath);
MyStaticChild.Save(FileNamePath);
doSomeThing(MyStaticChild.Payload.Attribute);
doSomething(MyStaticChild.AttributeBase);
doSomeThing(MyStaticChild.AttributeChild);
// ...
The person creating the static child does not need to think about the serialization process as long as they understand any limitations that might be placed on the platform's or environment's serialization engine.
Statics (singletons and other forms of 'globals') often come up around configuration storage. Static inheritance would allow this sort of responsibility allocation to be cleanly represented in the syntax to match a hierarchy of configurations. Though, as I showed, there is plenty of potential for massive ambiguity if basic static inheritance concepts are implemented.
I believe the right design choice would be to allow static inheritance with specific limitations:
No override of anything. The child cannot replace the base
attributes, fields, or methods,... Overloading should be ok, as
long as there is a difference in signature allowing the compiler to
sort out child vs base.
Only allow generic static bases, you cannot inherit from a
non-generic static base.
You could still change the same store via a generic reference MyStaticBase<ChildPayload>.SomeBaseField. But you would be discouraged since the generic type would have to be specified. While the child reference would be cleaner: MyStaticChild.SomeBaseField.
I am not a compiler writer so I am not sure if I am missing something about the difficulties of implementing these limitations in a compiler. That said, I am a strong believer that there is an informational space need for limited static inheritance and the basic answer is that you can't because of a poor (or over simple) design choice.
Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity.
A class can be declared static, which indicates that it contains only static members. It is not possible to use the new keyword to create instances of a static class. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace that contains the class is loaded.
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.
Following are the main features of a static class:
They only contain static members.
They cannot be instantiated.
They are sealed.
They cannot contain Instance Constructors (C# Programming Guide).
Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.
The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.
Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor; however, they can have a static constructor. For more information, see Static Constructors (C# Programming Guide).
When we create a static class that contains only the static members and a private constructor.The only reason is that the static constructor prevent the class from being instantiated for that we can not inherit a static class .The only way to access the member of the static class by using the class name itself.Try to inherit a static class is not a good idea.
I run into the problem when trying to code an IComparer<T> implementation against a third-party library where T is an enum embedded in a class as in the following:
public class TheClass
{
public enum EnumOfInterest
{
}
}
But because the enum is defined within a third-party library class, I can't write the comparer because the following gives a "cannot extends list" error:
public class MyComparer : IComparer<TheClass.EnumOfInterest>
{
}
I'm not even extending a static class -- I'm just implementing a comparer of a enum defined in a class.