In C#, what is the purpose of marking a class static?
If I have a class that has only static methods, I can mark the class static or not. Why would I want to mark the class static? Would I ever NOT want to mark a class static, if all the methods are static, and if I plan to never add a non-static method?
I looked around and saw some similar questions, but none that were just like this.
Marking a class as static is a declarative statement that you only intend for this type to have static and const members. This is enforced by the compiler and prevents you from accidentally adding an instance method to the type.
Other advantages
Extension methods can only be defined in static classes
Prevents users from creating an instance of the class
Prevents use of the type as a generic argument (thanks Eric!)
Marking a class as static gets you two important things.
Compiler verification that you only put static members in a class.
An obvious statement to readers of your code that this class is only a container for static members.
The feature was invented in response to a bug in NDP v1.0, where a un-callable non-static member was included in the System.Environment class.
If you would like to write extension methods, you have to use a static class. Otherwise it is to show the class will never have any instance data.
It is a convention specific to the C# language, the CLR has no notion of static classes. It ensures that you cannot accidentally add an instance member in the class, cannot inherit the class and client code cannot accidentally create an instance of the class. The underlying TypeAttributes for the class are Abstract and Sealed. Abstract ensures that the new operator can't work, Sealed ensures that you can't inherit from the class.
Also by convention, extension methods must be static members of a static class. VB.NET does it differently, it requires the [Extension] attribute.
Using static classes in your code is not necessary, but it is useful. Their contract is very descriptive, it makes your code easier to understand. But be careful not to use them as a vehicle to write procedural code instead of OOP code.
You mark a class static if you want to force it to contain only static methods, a typical helper class. If you put an instance method the compiler will complain - this is good. In version 1 of the .NET framework there was a class, don't remember which one, that was meant to ship with only static methods. Accidentally one of those methods did not get the static modifier. Because this feature did not exist at the time the bug was spotted very late, after shipping. They did make the constructor private and as such the method could not be used.
Related
I have a utility class that only contains static methods. If I mark the class as static, is that a breaking binary change?
I've compared the IL for both, and besides the loss of the default constructor (that should never be used), I can see the following differences...
Class not marked as static:
.class public auto ansi beforefieldinit MyNamespace.MyClass
Class marked as static:
.class public auto ansi abstract sealed beforefieldinit MyNamespace.MyClass
I can't see why that would be a breaking change, but...?
It depends on the usage of your class by other code: potential usage of static classes is a lot more restricted than that of non-static ones.
If the class has been used like static even though it hasn't been static at the time, the code is not going to break.
If the class has been used like non-static one, i.e. has been inherited or instantiated, then the change is breaking.
Since in general you cannot guarantee that your non-static class is used in a certain way, making a formerly non-static class a static one should be considered a breaking change. If you have code outside your control that depends on your class, designate the old class obsolete, and make a new static class to be used instead of it.
As you can see there are two modifiers added for static:
abstract: means you can't instantiate it
sealed: means you can't inherit from it
So in your code if you are instantiating this class or you have a type that inherits from it, your code will be broken.
Yes that is a breaking change. If the consumer of your library has subclassed your class, it will be broken.
Given that the class only contains bunch of static methods there is no point in inheriting it, but if someone did, that will stop their code from compiling.
Also note that you can't even declare a field of a type which is a static class. If the consumer had a field, property or something of your type, that will also break.
So the answer depends upon how the consumer library used it.
Why are virtual, abstract and override keywords not valid for Static function? What's the logic behind it?
Polymorphism via virtual dispatch is done by using the actual runtime type of the target instance, i.e. what the actual obj is in obj.Bar(...args...). Now: if you don't have a obj. instance, it makes no sense to discuss polymorphism.
Static methods are invoked with static-call, not virtual-call; the decision on what method to call is made entirely at compile time. There is no decision left to make. It comes down to the SomeType in SomeType.SomeMethod(...args...). You can of course still call between methods in a virtual method - you still have access to SomeBaseType.SomeOtherStaticMethod(...).
There are, in fact, languages out there that extend the polymorphism concept to static methods. C# isn't one of those languages, though. You are not allowed to call static functions through some kind of class reference, so you don't actually have a chance to do anything "polymorphic" there.
A static method is only really part of a particular class as a placeholder for the method. Static functions do not share lifetime or scope with the class they are declared in, and they are not really part of the object model.
These keywords (abstract, virtual, override) are related to an inheritance model and would have no meaning in a static context.
You shouldn't be accessing static methods through an instance. When you do, C# doesn't care about what type of object is in your variable; it goes by the type of the variable. That is, MyType obj = null; obj.StaticMethod(); works, because the object is never consulted. Scratch all that; in my version of Visual Studio, with default settings, you aren't even allowed to use a static method via an instance. Either way, that means virtual static wouldn't do anything worthwhile; virtual and override work by consulting the object to decide what method to use, and with static, you only have the type (which is effectively hard-coded, and thus rather useless with polymorphism). abstract being basically "requires an override in your class", it's not useful either.
I guess it wouldn't have been hard for the C# people to let you pretend static stuff could be overridden...but it can't. In order to call it, you have to specify the type (explicitly like MyType.StaticMethod(), or implicitly as mentioned above). They opted to make it clear that you can't have virtual static methods and have it work like you're expecting, by making it so you can't do it at all.
The keywords virtual, abstract and override are used with methods that are inherited. Static methods aren't inherited.
I have the following basic object factory for when I want some members of a class hierarchy to have special construction code and any other members to have generic constructors.
My problem here is that TileFactory doesn't have the method GetInstance--my program won't compile if I try to call TileFactory.GetInstance(). Any advice?
public static class ObjectFactory<K>
{
public static T GetInstance<T>() where T : K
{
T obj = (T)Activator.CreateInstance(typeof(T));
return obj;
}
//snip
}
}
//snip
public static class TileFactory : ObjectFactory<Tile>
{
}
Why can't I inherit static classes?
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.
http://www.dofactory.com/Patterns/PatternSingleton.aspx
There is no inheritance for static things. A workaround is to use singletons.
Why can't a static class be inherited into a normal class?
If B inherits from (is a subclass of) A, that means an instance of B can be stored in a variable of type A, and its virtual methods will call those of class B.
For static classes, you don't have the concept of an instance of the class, so there's no way to inherit. You might have better luck with a static (singleton) reference to a regular class.
From Static Classes and Static Class Members (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 contain a static constructor.
As an alternative to inheriting from a static class, you can assign extension methods to interfaces.
You can not inherit a static class - The reason is simple. Static classes are marked as abstract and sealed in compiled IL which can be neither instantiated nor inherited.
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)
Source:
Why can't I inherit static classes?
What is the use of a static class?
I mean what are benefits of using static class and how CLR deals with static classes?
A static class simply denotes that you don't expect or need an instance. This is useful for utility logic, where the code is not object-specific. For example, extension methods can only be written in a static class.
Pre C# 2.0, you could just have a regular class with a private constructor; but static makes it formal that you can never have an instance (there is no constructor*, and all members must be static).
(*=see comment chain; you can optionally have a type initializer (static constructor aka .cctor), but you cannot have an instance constructor (aka .ctor)).
The compilation and metadata model for .net requires that all functions are defined within a class. This makes life somewhat easier and simpler for the reflection api's since the concepts of the owning class and its visibility is well defined. It also makes the il model simpler.
since this precludes free functions (ones not associated with a class) this makes the choice of where to put functions which have no associated state (and thus need for an instance). If they need no state associated with them nor have any clear instance based class to which they can be associated and thus defined within there needs to be some idiom for their definition.
Previously the best way was to define the methods within a class whose constructor was private and have none of the functions within the class construct it.
This is a little messy (since it doesn't make it crystal clear why it was done without comments) and the reflection api can still find the constructor and invoke it.
Thus static classes were allowed, making the intent of the class, that of a place for the definition of static methods, clear to users and to the type system. Static classes have no constructor at all.
A static class is a language hack to write procedural programs in C#.
All members of a static class has to be static members, so, if you forget to add 'static' before any of them your code won't compile, it also makes your code more readable as anyone who will see that the class is static will understand it only contains static members.
The best use for a static class is for utility functions, you could also use them to keep the global methods and data in your application, I use static static classes very often in almost any project.
Static classes are often used to group related global services which you initially don't want to be accessed with an object instance. An example is the Math class in the .Net BCL, which you use directly, e.g., Math.Sqrt(10.0)
Static classes are sealed. This may be a useful option to use static for utility classes.
I got clear idea from this statements.
To know more about static class. First we must differentiate between static and instance data first.
Each time you create a new instance of a class you get a new copy of the instance data to play with. The instance methods of the class work on the instance data. The instance data is completely independent of the instance data in all other classes and even instances of the same class. If you change a value in one instance it has no impact on the same value in other instances. The bulk of program data is instance data.
Static data is equivalent to global data. Everybody in the program sees the same data. If someone changes the data then everybody else will see the change as well. Static data is useful for sharing information across a program such as database connection strings or log files. There is only one copy of static data in memory in general. (There are exceptions such as when dealing with multiple appdomains).
When you create an instance of a class you are effectively allocating some memory to hold your own copy of the instance data defined by the class. If you create 5 instances of a class then you get 5 separate memory locations where each location has its own copy of the instance data. Each memory block is independent of the others.
If a class has no instance data then it doesn't make any sense to create instances of it. Doing so is harmless but also a waste of time. This is where static classes come in. A static class is a way to identify a class as having no instance data. By marking the class as static you are telling the compiler that all the data in the class is shared across the board. As a result the compiler enforces some rules to make things clear. A static class can only contain static members. A static class cannot be instantiated. A static class must be sealed. The compiler enforces this for convenience of the developers.
A static class is sealed. This is because static classes cannot have per-instance data.
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 constructor is called once and the static class remains in the memory for the lifetime of the application domain in which your program resides.
Reference: http://msdn.microsoft.com/en-us/library/79b3xss3(VS.80).aspx
1.First of all u cannot create the instance for static classes
If the class declared as static, member variable should be static for that class
3.Sealed [Cannot be Inherited]
4.Cannot contains Instance constructor
5.Memory Management
Example: Math calculations (math values) does not changes [STANDARD CALCULATION FOR DEFINED VALUES]
In a class we declare a function as static,only if that function is not associated to any objects. We should not use "this" operator in that static function, because "this" operator will refers to object which invoke the function. Eg: Consider a class named Employee has few variables like Name, Age, Department, in this Employee class i am going to add a function called getSimilarNames() that will show How many employees having similar names. This function need not to be associated to any Employees. So I declare this function as a Static.If a class that only contains static functions, we declare that class is a static class. The Static function improves performance.