C # Struct Generic Constructor

Using this code:

struct Foo<T1> { public T1 Item1 { get; private set; } public Foo(T1 item1) { Item1 = item1; } } 

I ran into this error:

The backup field for the automatically implemented property "Foo.Item1" must be fully assigned before the control is returned to the caller. Consider calling the default constructor from the constructor initializer.

My question is: why is the Item1 property not fully assigned after the constructor call?

Edit: Changed set to private set because this question has nothing to do with volatility.

+7
source share
1 answer

Add this() here:

 public Foo(T1 item1) : this() { Item1 = item1; } 

This is because you assign a property, and the compiler cannot infer that the property assigns a value to a variable; it can do other things before the instance is initialized, and this is not allowed, since the structure may contain garbage data. Therefore, you must first initialize it with the default constructor, and then do what you want.

+15
source

All Articles