Hi friends,
I want to know that what's the difference between these initialization of integer x?
int x=1;
static int x=1;
Please explain the difference in the programming scenario?
Initialization of integer in C#
1 Answer
Know the answer? Post it. Somebody with the same question will find it here.


VulpesRank #55 · 29.2K reputationPosted Feb 14, 2012, 6:19 AM EST
static int x = 1;
assigns a private static field of type int an initial value of 1. As the field is static it applies to its containing class or struct as a whole and not to any particular instance of it. It can be accessed from anywhere within the containing class or struct but not from outside it and could be assigned a different value at a later date.
The first declaration:
int x = 1;
could mean one of two things:
1. It could be assigning a private instance field of type int an initial value of 1. As it's an instance field, it applies to an instance of its containing class or struct and could therefore be subsequently reassigned different values for different instances. It can be accessed from any instance method or property of the containing class or struct but not from a static member thereof or from outside it.
2. It could be assigning a local variable of an instance or static method or property of type int an initial value of 1. As it's a local variable it can only be accessed within its containing method or property and will be automatically destroyed when the method or property returns.