Thursday, May 8, 2008

Assignment in C#

What is difference between these three code snippets. All three snippets access a variable and compiler acts differently for each snippet. Tell me the answers in comment

a)
static void Main( )
{
int x;
Console.WriteLine (x);
}

b)
static void Main( )
{
int[] ints = new int[2];
Console.WriteLine (ints[0]);
}

c)
class Test
{
static int x;
static void Main( ) { Console.WriteLine (x); }
}

6 Comments :

Param said...

the static int variable it contains zero by default as well as array too. while using unassign variable the compiler shows an error

Siva said...

Senthil, Thanks for the post (it’s really helpful to understand the basic concepts)

OK now let me detail my understanding,

a) int x; All primitive types are value type and the memory will be assigned only if the variable is assigned while runtime.

b) int[] ints = new int[2]; An array in .net is reference type, so the memory will be created for both the reference and object at runtime. That’s why we are using new keyword before we start using the array.

c) static int x; As everyone known we don’t need to instantiate a static class, so the same will do with static variable also because the runtime will automatically create a single instance (memory) by itself.

Siva said...

Senthil, Thanks for the post (it’s really helpful to understand the basic concepts)

OK now let me detail my understanding,

a) int x; All primitive types are value type and the memory will be assigned only if the variable is assigned while runtime.

b) int[] ints = new int[2]; An array in .net is reference type, so the memory will be created for both the reference and object at runtime. That’s why we are using new keyword before we start using the array.

c) static int x; As everyone known we don’t need to instantiate a static class, so the same will do with static variable also because the runtime will automatically create a single instance (memory) by itself.

செந்தில் குமார் இராமச்சந்திரன் / Senthil Kumar Ramachandran said...

Thank you Paramu and Siva for your answers.

Ok, Answerer for this post is,
In C# compiler follows the below rules for assignment
1) All fields in struct, class, array initialized by CLR at Runtime
2) Function parameters has to be assigned when function is called
3) Local variable has to be assigned before they used

So, when we apply this rule to the snippets in the blog,
Snippet a) >> compilation error, Bcoz local variable is not assigned before it used
Snippet b) Prints 0, as per the rule 1)
Snippet c) Prints 0, as per the rule 1)
Snippet

Anonymous said...

a)
when executed will given an error due to

use of unassigned local variable x because c# follows definite assignment rule. So we have to initialize before assigning

b)the variable is declared as array with size 2.It returns the 0 the value of the first index of the array ie,(0,1)

c)returns 0 as static variables are
initialized at runtime

Anonymous said...

you have a wonderful site!