In this post let us try to explore what is static keyword in C#
Definition of static keyword
As per MSDN, “Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object.”
So it means that static keyword should be used with types which provide generic functionality and it doesn’t make sense to create objects of that type. For example, consider the System.Math class in c#. It provide various mathematical functions which can be used in the code as per requirements. And it doesn’t make sense to create an object of Math class to use those functions. Rather a typical usage will be like Math.Floor(0.5).
How CLR handles the static keyword
When a type is declared as static, CLR would:
- Emit static keyword as abstract and sealed. What this means is that the type would become abstract and sealed. Sealed would make sure that type cant be further inherited.
- It also doesn’t emit the default constructor in the type.This also means that since there is no contructor in the type, no instance for this type can be created.
Some restrictions on using the Static keyword
- A static keyword can only be applied to reference types. Keyword cannot be applied on value types(like structures) because CLR always create instances of value types.
- Static class can contain only static members(fields, properties, methods). This is because static class cannot refer to any instance members.
- As already mentioned above, static class cannot be instantiated. Hence static class cannot be used in a manner which signifies it being used for some specific instance.
Hope above explanation clears the concepts regarding static keyword. If there are any questions you can post them and I would be happy to address them.