"static" Keyword in C#

Mannan Ul Haq
0
In C#, the `static` keyword is used to declare members that belong to the type itself rather than to instances of the type. `static` members are part of the class and not the instances of that class. Hence, you do not need to create an object of that class to use a `static` member. The `static` keyword can be used with fields, methods, properties, constructors, classes, etc.

Static Fields/Variables:

A static field, also known as a class variable, is a variable that belongs to the class rather than an instance of the class. This means there is only one copy of the static field, and its value is shared among all instances of the class. 

class MyClass
{
    public static int myStaticField;
}

Usage:

MyClass.myStaticField = 100;
Console.WriteLine(MyClass.myStaticField); // Outputs: 100

Here, `myStaticField` is a static field. You do not need to create an instance of `MyClass` to use `myStaticField`.

Static Methods:

A static method is a method that belongs to the class rather than an instance of the class. You can call a static method without creating an instance of the class.

class MyClass
{
    public static void MyStaticMethod()
    {
        Console.WriteLine("This is a static method.");
    }
}

Usage:

MyClass.MyStaticMethod(); // Outputs: This is a static method.

Here, `MyStaticMethod` is a static method. You do not need to create an instance of `MyClass` to call `MyStaticMethod`.

Static Classes:

A static class is a class that cannot be instantiated or inherited. In other words, you cannot use the `new` keyword to create an instance of the class, and you cannot use the class as a base class for other classes. A static class can only contain static members.

static class MyStaticClass
{
    public static void MyStaticMethod()
    {
        Console.WriteLine("This is a static method in a static class.");
    }
}

Usage:

MyStaticClass.MyStaticMethod(); // Outputs: This is a static method in a static class.

Here, `MyStaticClass` is a static class, and `MyStaticMethod` is a static method in `MyStaticClass`. You do not create an instance of `MyStaticClass` to call `MyStaticMethod`.

Tags

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !