Wednesday, January 03, 2007 3:50 AM bart

C# Quiz - Field initialization

Saw a good question on the discussion lists yesterday:

What is the difference (practically) in assigning a variable value in the variable declaration line and in the constructor?

So, here's the quiz question: What's the difference between the following two code fragments?

Fragment 1:

class Bar { private int i = 123; public Bar() { } }

Fragment 2:

class Bar { private int i; public Bar() { i = 123; } }

Tip: the difference is rather subtle.

I'll post another code fragment for this quiz tomorrow "on the road to the solution".

Del.icio.us | Digg It | Technorati | Blinklist | Furl | reddit | DotNetKicks

Filed under:

Comments

# re: C# Quiz - Field initialization

Wednesday, January 03, 2007 4:21 AM by Ramon

The data member i is initialized twice? First with the default 0 and then with 123?

# re: C# Quiz - Field initialization

Wednesday, January 03, 2007 4:35 AM by Ramon

My previous comment isn't true. Just checked the IL: .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 15 (0xf) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.s 123 IL_0003: stfld int32 A::i IL_0008: ldarg.0 IL_0009: call instance void [mscorlib]System.Object::.ctor() IL_000e: ret } // end of method A::.ctor .method private hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 15 (0xf) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldc.i4.s 123 IL_0009: stfld int32 B::i IL_000e: ret } // end of method B::.ctor The only difference I see is that i is initialized before or after calling the base class constructor which is quite logical.

# re: C# Quiz - Field initialization

Wednesday, January 03, 2007 6:43 AM by Bassam Basamad

Hi Mr Bart, I think the first it will give default value as 123 and the second will give default value as 0 in (Class Scope). i mean when make new object from the class as asuming that the varible is publica not private so when i access the value it will be deffiernet for two conditions. and this means that the first way, is not good that it will load all the variable values, and i think when you load less values is better. this is my opinion.. thanks. hope this true.

# re: C# Quiz - Field initialization

Wednesday, January 03, 2007 10:01 AM by Kris

The static initializer (cctor) for the first code sample assigns the member variable prior to the default constructor call. The second sample assigns the member variable withing the (ctor).

# re: C# Quiz - Field initialization

Wednesday, January 03, 2007 12:15 PM by zproxy

Ramon is right:) The only difference is that the field initializer has no access to this variable.

# Answers to C# Quiz - Field initialization

Monday, January 08, 2007 1:20 PM by B# .NET Blog

A few days ago I posted the following two posts for this C# Quiz: C# Quiz - Field initialization C# Quiz