C# static Keyword with Examples

In C#, the static keyword is used to declare members, methods, properties, and fields that belong to the class instead of instances of the class. This means that static members can be accessed using the class name, without the need to create an instance of the class.

Declaring a Static Member

To declare a static member, you need to add the static keyword before the member type. Here's an example of a static field:

1class MyClass 2{ 3 static int myStaticField = 10; 4}

In this example, the myStaticField field is a static field and is initialized to the value of 10.

Accessing Static Members

You can access a static member using the class name, like this:

1int value = MyClass.myStaticField;

In this example, the myStaticField field is accessed using the MyClass class name.

Static Constructors

A static constructor is a special type of constructor that is used to initialize the static fields of a class. The static constructor is called only once, before the first instance of the class is created. Here's an example of a static constructor:

1class MyClass 2{ 3 static int myStaticField; 4 5 static MyClass() 6 { 7 myStaticField = 10; 8 } 9}

In this example, the static constructor initializes the value of myStaticField to 10.

Static Classes

In C#, you can also declare a class as static. A static class can only contain static members and cannot be instantiated. Here's an example of a static class:

1static class MyStaticClass 2{ 3 static int myStaticField = 10; 4}

In this example, MyStaticClass is a static class and contains a static field called myStaticField.

Benefits of Using Static Members

There are several benefits of using static members in C#:

  • static members can be accessed without creating an instance of the class, which can save memory and improve performance.
  • static members can be used to store data that is shared among all instances of the class.
  • static members can be used to create utility classes, which contain a set of related static methods.