Static keyword has different role in different places for C#. When we declare static that means only single copy will be generate.
Static container can only contains static members
It is used in below places-
Static Class
Static Methods
Static Fields
Static Constructor
More About Static:
Static container can only contains static members
It is used in below places-
- Class
- Method
- Field
- Properties
- Constructor
Static Class
- Only contain all static members like static methods, static fields, static properties and static constructor.
- Any instance or non-static member can not be there in the Static Class.
- If we need to create all the members as static then we can create static class.
- Can not create instance of such class.
- Sealed.
- Cannot contain Instance Constructors
Static Methods
- Only contain all static fields
- Non-static fields are not allowed in static methods
- Method can be access using class only, no instance is needed or can access.
- Single copy of static method will be shared among all the instances.
Static Fields
- Single copy of fields/variables get created and shared among all the instances.
- If static variable value has been change using one instance then all other instance will get that changed value.
Static Property
- Can be access using class only.
- Using instance it can not be access.
Static Constructor
- Access modifier are not allowed.
- Static Constructor as it(class constructor) execute prior to any other constructor (instance constructor).
- Can instantiate value of static fields only.
- Non-Static fields is not allowed within the scope.
More About Static:
- Static methods are not allowed in the interface.
- Access modifiers are not allowed in the interface and static constructor.
- Static class can't be inherit from interface/class/static class.
- Static class can only be inherit from object. ??
- Inheritance from static class in not possible as static classes are sealed.
- Inherited Static method can not be marked as override, virtual or abstract.
- Inherited Static methods can be marked as new.