The static keyword in C# is refering to something in the class, or the class itself, that is shared amongst all instances of the class.
Static:A C#class can contain both static and non-static members. When we declare a memberwith the help of the keyword static, it becomes a static member. We access datamember without creating object.
Static Fields: Static field can be declared as follows by using thestatic keyword.
Example:
class myclass
{
public static int x;
public static int y = 20;
}
When we declare a static field inside a class, it can beinitialized with a value as shown above. All un-initialized static fieldsautomatically get initialized to their default values when the class is loadedfirst time.
Static Member Functions: Inside a C# class,member functions can also be declared as static. But a static member functioncan access only other static members. They can access non-static members onlythrough an instance of the class. We can invoke a static member only throughthe name of the class.
Example:
class myClass
{
private staticint x = 20;
private static int y = 40;
public static void method()
{
Console.WriteLine("{0},{1}", x, y);
}
}
class myClsInit
{
public static void main()
{
myClass.method();
}
}
The output will be:
20, 40
Manish Kumar
14-Jun-2017It was really helpful to read this post.