C# Struct Generic Constructor [duplicate]
Using this code:
struct Foo<T1>
{
public T1 Item1 { get; private set; }
public Foo(T1 item1)
{
Item1 = item1;
}
}
I encounter this error:
Backing field for automatically implemented property 'Foo.Item1' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer.
My question is, why is the p开发者_开发百科roperty Item1
not fully assigned after the constructor is called?
Edit: Changed set
to private set
because this question has nothing to do with mutability.
Add this()
in here:
public Foo(T1 item1) : this()
{
Item1 = item1;
}
It's because you're assigning to a property, and the compiler can't deduce that the property only assigns a value to a variable; it could do other things before the instance is initialized, and that's not allowed because the structure might have garbage data. So you have to initialize it with the default constructor first, then do what you want.
精彩评论