The static modifier can be used with fields, properties, methods, events, constructors, operators and classes. You can not use static modifier with destructors, indexers and types other than classes.
A type or a constant declaration is implicitly static, so that any type defined in class directly accessed by class name.
public class MyBaseC { public struct MyStruct { public static int x = 100; } }
Console.WriteLine(MyBaseC.MyStruct.x);
Static class
Members of the static class called by the name of class.
Making a class with all static members and a private constructor is same as creating a static class, because a private constructor protects a class to be instantiated.
1. Can’t be instantiated.
2. Can’t be inherited.
3. Can contain only static members.
4. Sealed by default, they can not inherit from any class except Object class.
5. Can’t contain instance constructor, can contain static constructor.
class myClass
{
public class myStaticClass
{
public static int Age;
public static void Display(int x)
{
//Method implementation
}
}
public static void main()
{
myStaticClass.Age = 30;
myStaticClass.Display(55);
}
}
Static members
Can be used to count no. of instances created or to stores some value that is shared b/w all instances.
Terminology
1. Static methods / properties can’t access other non-static members.
2. Static methods can be overloaded and can’t be overridden because they belong to class not to instance.
3. Constants can’t be declared static, because they are by default static.
4. C# does not support static local variables (variables that are declared in method scope).
{
public static string GetCompanyName() { return "CompanyName"; }
}