What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

344,604

Solution 1

A static variable shares the value of it among all instances of the class.

Example without declaring it static:

public class Variable
{
    public int i = 5;
    public void test()
    {
        i = i + 5;
        Console.WriteLine(i);
    }
}


public class Exercise
{
    static void Main()
    {
        Variable var = new Variable();
        var.test();
        Variable var1 = new Variable();
        var1.test();
        Console.ReadKey();
    }
}

Explanation: If you look at the above example, I just declare the int variable. When I run this code the output will be 10 and 10. Its simple.

Now let's look at the static variable here; I am declaring the variable as a static.

Example with static variable:

public class Variable
{
    public static int i = 5;
    public void test()
    {
        i = i + 5;
        Console.WriteLine(i);
    }
}


public class Exercise
{
    static void Main()
    {
        Variable var = new Variable();
        var.test();
        Variable var1 = new Variable();
        var1.test();
        Console.ReadKey();
    }
}

Now when I run above code, the output will be 10 and 15. So the static variable value is shared among all instances of that class.

Solution 2

C# doesn't support static local variables (that is, variables that are declared in method scope).

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members#static-members

You can declare static fields (class members) though.

Reasoning: Static field is a state, shared with all instances of particular type. Hence, the scope of the static field is entire type. That's why you can't declare static instance variable (within a method) - method is a scope itself, and items declared in a method must be inaccessible over the method's border.

Solution 3

static variables are used when only one copy of the variable is required. so if you declare variable inside the method there is no use of such variable it's become local to function only..

example of static is

class myclass
{
    public static int a = 0;
}

Variables declared static are commonly shared across all instances of a class.

Variables declared static are commonly shared across all instances of a class. When you create multiple instances of VariableTest class This variable permanent is shared across all of them. Thus, at any given point of time, there will be only one string value contained in the permanent variable.

Since there is only one copy of the variable available for all instances, the code this.permament will result in compilation errors because it can be recalled that this.variablename refers to the instance variable name. Thus, static variables are to be accessed directly, as indicated in the code.

Solution 4

Some "real world" examples for static variables:

building a class where you can reach hardcoded values for your application. Similar to an enumeration, but with more flexibility on the datatype.

public static class Enemies
{
    public readonly static Guid Orc = new Guid("{937C145C-D432-4DE2-A08D-6AC6E7F2732C}");
}

The widely known singleton, this allows to control to have exactly one instance of a class. This is very useful if you want access to it in your whole application, but not pass it to every class just to allow this class to use it.

public sealed class TextureManager
    {
        private TextureManager() {}
        public string LoadTexture(string aPath);

        private static TextureManager sInstance = new TextureManager();

        public static TextureManager Instance
        {
            get { return sInstance; }
        }
    }

and this is how you would call the texturemanager

TextureManager.Instance.LoadTexture("myImage.png");

About your last question: You are refering to compiler error CS0176. I tried to find more infor about that, but could only find what the msdn had to say about it:

A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events.

Solution 5

Static variables are used when only one copy of it is required. Let me explain this with an example:

class circle
{
    public float _PI =3.14F;
    public int Radius;

    public funtionArea(int radius)
    {
        return this.radius * this._PI      
    }
}
class program
{
    public static void main()
    {
        Circle c1 = new Cirle();
        float area1 = c1.functionRaduis(5);
        Circle c2 = new Cirle();
        float area2 = c1.functionRaduis(6);
    }
}

Now here we have created 2 instances for our class circle , i.e 2 sets of copies of _PI along with other variables are created. So say if we have lots of instances of this class multiple copies of _PI will be created occupying memory. So in such cases it is better to make such variables like _PI static and operate on them.

class circle
{
    static float _PI =3.14F;
    public int Radius;

    public funtionArea(int radius)
    {
        return this.radius * Circle._PI      
    }
}
class program
{
    public static void main()
    {
        Circle c1 = new Cirle();
        float area1 = c1.functionRaduis(5);
        Circle c2 = new Cirle();
        float area2 = c1.functionRaduis(6);
    }
}

Now no matter how many instances are made for the class circle , only one copy exists of variable _PI saving our memory.

Share:
344,604

Related videos on Youtube

Kartik Patel
Author by

Kartik Patel

Updated on October 21, 2021

Comments

  • Kartik Patel
    Kartik Patel over 2 years

    I have searched about static variables in C#, but I am still not getting what its use is. Also, if I try to declare the variable inside the method it will not give me the permission to do this. Why?

    I have seen some examples about the static variables. I've seen that we don't need to create an instance of the class to access the variable, but that is not enough to understand what its use is and when to use it.

    Second thing

    class Book
    {
        public static int myInt = 0;
    }
    
    public class Exercise
    {
        static void Main()
        {
            Book book = new Book();
    
            Console.WriteLine(book.myInt); // Shows error. Why does it show me error?
                                           // Can't I access the static variable 
                                           // by making the instance of a class?
    
            Console.ReadKey();
        }
    }
    
    • Dennis
      Dennis about 12 years
      May be you mean "static field"?
    • Kartik Patel
      Kartik Patel about 12 years
      Like we declare in class static int i=5
    • user1703401
      user1703401 about 12 years
      VB.NET supports local static variables. They had to implement it to stay compatible with vb. The amount of code it generates is enormous, local statics are difficult because they are not thread-safe. Fields are not thread-safe either, but everybody expects that.
    • Pranay Rana
      Pranay Rana about 12 years
      dont forget to mark answer as accepted if you got the info you want...
    • Jaider
      Jaider over 9 years
      You can access static variables/methods through the type (in this case Book) no through an instance (book), so the easier solution is Book.myInt.
  • Kartik Patel
    Kartik Patel about 12 years
    can you please explain with example?
  • Kartik Patel
    Kartik Patel about 12 years
    but if i make the instance of a class then i am not able to access static variable.why?I can access the static variable by classname.variable only not by making the instance of a class................
  • dowhilefor
    dowhilefor about 12 years
    @Kartik Patel because you have to use the class name to access the static myInt. Why it like this, i don't know. But i would say that it is much clearer because you want to access a static part of the class, it is not static if you need an instance to access it.
  • Kartik Patel
    Kartik Patel about 12 years
    @dowhilefor:But as you mentioned above that "Variables declared static are commonly shared across all instances of a class." then what is the meaning of this?
  • dowhilefor
    dowhilefor about 12 years
    @Kartik Patel you can't access the variable from the outside with an instance, but you can always use the static variable inside your class and then it is shared accross all instances. Also it was not me who gave this answer, i'm just commenting on it.
  • Kartik Patel
    Kartik Patel about 12 years
    @dorwhilefor:sorry i just see that you just commenting on it havent answered.but can you Please show me the example of it?
  • Kartik Patel
    Kartik Patel about 12 years
    @Pranay:Yes thats better but if you show me example that i show above than it cound be better for me and others....anyway good effort....
  • chwi
    chwi over 10 years
    It is static to the class, i.e its value remains faithful to the class with its value stored in its... wait for it... class
  • Kokodoko
    Kokodoko over 9 years
    You say a static variable is shared among all instances of the class... but what if there are no instances? Can you still set a variable? Is it allowed to store dynamic data in a static class?
  • Ladmerc
    Ladmerc almost 9 years
    @Kokodoko, even if there is no instance, you surely can set the variable. That defines its static nature
  • Teoman shipahi
    Teoman shipahi over 7 years
    Well, in documentation it is stated as "A field declared with the static modifier is called a static variable." msdn.microsoft.com/en-us/library/aa691162(v=vs.71).aspx But you are right on rest of the explanation.
  • leonidaa
    leonidaa over 5 years
    very good observation because if you try to use object to access the value of property myInt the you will get an error : static void Main() { Book book = new Book(); // this give you error : book.myInt =5 ;
  • leonidaa
    leonidaa over 5 years
    exactly , see @Kunal Mukherjee example from above
  • Dan
    Dan over 3 years
    And you can add readonly to _PI variable so that no instance can change its value.
  • gawkface
    gawkface over 2 years
    @Teomanshipahi updated link: docs.microsoft.com/en-us/dotnet/csharp/language-reference/… : (the link has difference between static and instance variable)