Ivan Glasenberg
Ivan Glasenberg

Reputation: 29950

why we cannot initialize an instance field at declaration in c# struct?

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.
}

Upvotes: 0

Views: 285

Answers (1)

Davey van Tilburg
Davey van Tilburg

Reputation: 718

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

Upvotes: 1

Related Questions