Static Readonly variables

Why Static variables?

static variable shared the value of it among all instances of the class. Changes done to static variable are visible across methods. Static variable, that means it exists exactly one place in memory for the duration of the program. Static class variables are like globals. Static variables belong to type, not to its instance. You can change the value of a static variable in any of the method of that 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 int variable.when i run this code the output will be 10 and 10.

Now Lets 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 then the output will be 10 and 15. so static variable value shared among all instances of that class.

Now  Readonly

class Age

{

readonly int _year;  // Readonly prevents fields from being changed.

Age(int year)

{

_year = year; // We can assign at the time of readonly variable declaration  or in a constructor in the same class.

}

void ChangeYear()

{

//_year = 1967; // Compile error if uncommented.

}

}

 But  static readonly will not allow to set inside of methods.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s