When i create an Object which one will be called to initialized first from compiler field , properties , static members? what is the right order of setting default value for each one ?
Asked
Active
Viewed 720 times
1
-
3There is no correct order for setting default values that I've ever heard of. Usually the defaults are set at declaration or in a constructor. – Rufus L Apr 24 '18 at 06:23
-
If it matters, you're probably doing something wrong (i.e. if there are dependencies between your initializers, you're probably better off moving them into (static/instance) constructors and explicitly controlling the order rather than being "clever" and knowing what order they'll be initialized in) – Damien_The_Unbeliever Apr 24 '18 at 06:25
-
i want to know how compiler work with this fields and set the default value for every type . i know compiler will set value of each one as it's written in constructor but which one is intialized first ? – ahmed khattab Apr 24 '18 at 06:26
-
then is static fields in static constructor will be called first ? – ahmed khattab Apr 24 '18 at 06:27
-
1Any chance you could write a concrete example in your question? It's not clear what you mean by "static fields in static constructor" for example. It's much easier to talk about specific code. – Jon Skeet Apr 24 '18 at 06:32
-
1Create a test assembly, grab a decompiler and check yourself what the compiler did. – thehennyy Apr 24 '18 at 06:33
-
1kind of related: https://stackoverflow.com/questions/1882692/c-sharp-constructor-execution-order – rene Apr 24 '18 at 06:38
-
@thehennyy: While that certainly goes some way towards an answer, it wouldn't tell you which aspects of the behaviour are *guaranteed* by the specification rather than implementation-specific for that compiler. – Jon Skeet Apr 24 '18 at 07:24
2 Answers
0
Whenever you reach to any class in c# for the first time then static constructor of that class will be initialized first. So you can put static members into that constructor and that will be initialized first.

Ravi Mungalpara
- 14
- 5
-
2
-
@@rene still you can assign value to static members and those will be intialized first and then instance members – Ravi Mungalpara Apr 24 '18 at 06:40
-
-
I think first static fields, then static constructor and then instance fields and instance constructor and so.... – Ravi Mungalpara Apr 24 '18 at 06:43
-
It is better backed by evidence instead of a guess. These things might matter. – rene Apr 24 '18 at 06:49
-
I found one example from here : http://www.csharp411.com/c-object-initialization/ – Ravi Mungalpara Apr 24 '18 at 07:19
0
Static members are initialized before any static member is accessed and also before the static constructor is called. They are initialized in the same order as they appear in the code. The static constructor guaranteed to be called before the first instance of the class is created.

armenm
- 922
- 6
- 9