3

I have a doubt.

1. namespace JIMS.ViewModel.Stock
2. {
3.     internal class StockGroupViewModel : JIMS.ViewModel.BaseViewModel
4.     {
5.         JIMSEntities dbContext = new JIMSEntities();
6. 
7.         public StockGroupViewModel()
8.         {                     
9.          dbContext = new JIMSEntities();
10.        }
11.    }
12. }

I have this class. And i want to know which is called first. when i create an instance of this class

StockGroupViewModel s = new StockGroupViewModel();

Line 5 or Line 9.

Kishore Kumar
  • 12,675
  • 27
  • 97
  • 154

4 Answers4

12

Line 5 - it's a field initializer which is executed before any code within the constructor.

From the spec:

10.5.5.2 Instance field initialization

The instance field variable initializers of a class correspond to a sequence of assignments that are executed immediately upon entry to any one of the instance constructors (§10.11.1) of that class. The variable initializers are executed in the textual order in which they appear in the class declaration. The class instance creation and initialization process is described further in §10.11.

Community
  • 1
  • 1
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
2

Field initializers called prior to body of constructor. So, line 5 called before line 9.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
1

Line 5, fields are initialized before constructor is called.

ABH
  • 3,391
  • 23
  • 26
1

The compiler will embed the field initializer in the code for the constructor, so that is called first and then the field is initialized again by the call in the constructor. Looking at the IL for the code makes this very obvious.

E.g. code like this

class Foo
{
    StringBuilder sb = new StringBuilder(1);

    public Foo()
    {
        sb = new StringBuilder(2);
    }
}

looks like this at the IL level

.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
    .maxstack 8
    L_0000: ldarg.0 
    L_0001: ldc.i4.1  <-- ARGUMENT = 1
    L_0002: newobj instance void [mscorlib]System.Text.StringBuilder::.ctor(int32)
    L_0007: stfld class [mscorlib]System.Text.StringBuilder playground.Foo::o
    L_000c: ldarg.0 
    L_000d: call instance void [mscorlib]System.Object::.ctor()
    L_0012: nop 
    L_0013: nop 
    L_0014: ldarg.0 
    L_0015: ldc.i4.2  <-- ARGUMENT = 2
    L_0016: newobj instance void [mscorlib]System.Text.StringBuilder::.ctor(int32)
    L_001b: stfld class [mscorlib]System.Text.StringBuilder playground.Foo::o
    L_0020: nop 
    L_0021: ret 
}
Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317