1

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 ?

ahmed khattab
  • 2,311
  • 3
  • 16
  • 30
  • 3
    There 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
  • 1
    Any 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
  • 1
    Create a test assembly, grab a decompiler and check yourself what the compiler did. – thehennyy Apr 24 '18 at 06:33
  • 1
    kind 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 Answers2

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.

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