5

I am surprised that I can't initialize my fields in structs, why is it like that? Like:

struct MyStruct
{
    private int a = 90;
}

but it's a complie time error. I don't know why it's a problem? Please explain this to me.

Jon Limjap
  • 94,284
  • 15
  • 101
  • 152
Embedd_0913
  • 16,125
  • 37
  • 97
  • 135

4 Answers4

11

In C#, a struct cannot declare a default constructor.

The compiler moves the initialization statements to the constructor, which can't happen with a struct in C#.

Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
3

The reason is mainly performance. Consider the following,

var a = new MyStruct[1000];

If C# allowed initialization of fields in a struct then the initialization would have to be performed 1000 times, once for each element in the array. C# wanted to avoid such kinds of implicit behavior as might be found in other languages.

chuckj
  • 27,773
  • 7
  • 53
  • 49
  • 2
    No offense but why not let the creator of the struct decide? Nothing to lose. And it would have been nice if values of fields initialized this way, would be used by `default(TheSaidStruct)` instead of just zero filling. – mireazma Oct 14 '20 at 17:30
3

That's because your assignment is actually transformed by the compiler to be done in the default constructor. But C# structs don't have default constructors, as you can see in the link posted by Kent Boogaart.

Community
  • 1
  • 1
Hosam Aly
  • 41,555
  • 36
  • 141
  • 182
0

It's for performance. When you new up a struct with the default constructor, all it does is allocate however many bytes on the stack and initialises them to 0.

TraumaPony
  • 10,742
  • 12
  • 54
  • 74