Why is it necessary to initialize all fields in meaningful C # types, if there is a constructor?

For example, the following code will not compile

struct AAA { public int A; public string C; public AAA(int a) { A = a; } } 

The AAA.C field must be fully defined before returning control to the calling method.

But if we remove the constructor, then everything compiles

 struct AAA { public int A; public string C; } 

1 answer 1

The fact is that for structures, as opposed to classes, there is no initialization of fields by default (for the sake of efficiency). If you do not define a constructor, then you have a default constructor that initializes all fields to zero (the default appropriate type). If you define your constructor, it is enough to call the default constructor:

 public AAA(int a) : this() { A = a; } 

Without this, the C field would not be initialized, and the value would not be defined. Such situations C #, unlike C ++, does not allow.

  • and there was no duplicate? I think about the structure of a straight recently was still - Grundy
  • @Grundy: I ​​don't seem to remember the exact duplicate. - VladD
  • Yeah, I already ran, looked. There's a bit about another questions :-) - Grundy