Translate

Tuesday 16 December 2014

what is the use of static variable in c#?When to use it?why cant i declare the static variable inside Method?


static variable is used to shared the value of it among all instances of the class.

Example:

public  class Variable
{
    public int i = 5;    // 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();
    }
}

Output:  10  10

if declare the varaible as static, Then the output is 10 15

No comments:

Post a Comment