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. } 
4
  • Does this answer your question? C# compiler error: "cannot have instance field initializers in structs" Commented Apr 20, 2020 at 5:27
  • @Martheen, Thanks. I did take a look at this, but still not very clear:(. Commented Apr 20, 2020 at 5:28
  • The linked answer should shed more light 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.". Commented Apr 20, 2020 at 5:37
  • @Martheen, thanks again. I'll take a look. Commented Apr 20, 2020 at 5:43

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.