Static Classes and Static Class Members in C# - ablealias/asp.net GitHub Wiki
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
. Because there is no instance variable, you access the members of a static class by using the class name itself
. For example, if you have a static class that is named UtilityClass that has a public method named MethodA, you call the method as shown in the following example:
UtilityClass.MethodA();
The following list provides the main features of a static class:
- Contains only static members.
- Cannot be instantiated.
- Is sealed.
- Cannot contain Instance Constructors.
A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name
, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created. Static methods and properties cannot access non-static fields and events
in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.
C# does not support static local variables (variables that are declared in method scope).
Extension Methods are static methods.
public static class ExtensionMethod{
public static string ToAppend(this string fullname, string str1, string str2)
{
return fullname + " " + str1 + " " + str2;
}
}
Static members are stored in a special area inside the heap called High Frequency Heap. Static members of non-static classes are also stored in the heap and shared across all the instances of the class. So the changes done by one instance will be reflected in all the other instances.