0

In c# -> struct, we cannot assign a value to instance field at declaration. Can you tell me the reason? Thanks.

A simple example:

struct Test
{
  public int age =10; // it's not allowed.
}
Ivan Glasenberg
  • 29,865
  • 2
  • 44
  • 60
  • Does this answer your question? [C# compiler error: "cannot have instance field initializers in structs"](https://stackoverflow.com/questions/4406178/c-sharp-compiler-error-cannot-have-instance-field-initializers-in-structs) – Martheen Apr 20 '20 at 05:27
  • @Martheen, Thanks. I did take a look at this, but still not very clear:(. – Ivan Glasenberg Apr 20 '20 at 05:28
  • The linked answer should shed more light https://stackoverflow.com/a/333840/529282 especially the matter of "The CLR is able to do this very efficiently just by allocating the appropriate memory and zeroing it all out.". – Martheen Apr 20 '20 at 05:37
  • @Martheen, thanks again. I'll take a look. – Ivan Glasenberg Apr 20 '20 at 05:43

1 Answers1

1

I think the answer is very simple, but hard to get a grasp of if you do not know the difference between value types and reference types.

Maybe something to note is that reference type are held in the heap, which the garbage collect cleans. And a value type lives in the stack. Every time you define a scope, like:

{ 
}

A new local stack is created. Once you exit this scope, all value types on the stack are disposed unless a reference is held to them on the heap.

Seeing as reference types and value types are very differently handled, they are also designed with these changes in mind. Not being able to have empty constructors and also not being able to assign values on construction is a logical result of this.

I found a very old stackoverflow question regarding the same, they also have some short answers regarding it being designed like that for performance reasons:

Why can't I initialize my fields in my structs?

My source for this info was the ref book for 70-483.

Hope this gave you the clarification you are looking for