Friday, May 12, 2023

Static variable in C#

 What is static variable in C#?


In C#, a static variable (also known as a class variable) is a variable that belongs to a class rather than to any particular instance of the class. A static variable is shared by all instances of the class and can be accessed without creating an instance of the class.


You can declare a static variable using the "static" keyword followed by the variable type and name:



class MyClass {

    public static int myStaticVar; // a static variable

}


In this example, we declare a static variable named "myStaticVar" of type int in the MyClass class. Once a static variable is initialized, it remains the same throughout the lifetime of the program.


Static variables are useful when you have a value that needs to be shared by all instances of a class. For example, you might use a static variable to keep track of the number of instances of a class that have been created:



class MyClass {

    public static int numInstances = 0; // a static variable


    public MyClass() {

        numInstances++;

    }

}



In this example, we declare a static variable named "numInstances" that is used to count the number of instances of the MyClass class that have been created. We increment the value of "numInstances" in the constructor of the class. Since "numInstances" is a static variable, it is shared by all instances of the MyClass class, and the value of "numInstances" will be incremented each time a new instance of the class is created.


Static variables can also be used to create global data that can be accessed from anywhere in the program, as long as the class that declares the static variable is visible to the code that needs to access it.

No comments:

Post a Comment

If you have any query kindly let me know.

Blazor drawback| drawback of blazor| Disadvantage of blazor in c#

  Blazor drawback| drawback of blazor| Disadvantage of blazor in c# While Blazor offers many advantages, it also has a few drawbacks to cons...