Well, for a start you're creating a mutable struct - that's almost always a really bad idea. Mutable structs can sometimes behave in ways you don't expect. Okay, it's only privately mutable, but the fact that you've written code to mutate it is a bad sign.
The reason for the second error is that you can't use any properties or methods of the struct until all fields have been assigned, so you need to chain to the implicit parameterless constructor:
public T(int u) : this()
{
this.U = 10;
}
The compiler requires that any constructor leaves all the fields definitely assigned (which is why you were getting the first error before; the compiler doesn't "know" that the property assigns the field a value) - by chaining to this()
, you're making sure that by the time you get to your constructor body, all the fields are already definitely assigned, and you don't need to worry about it any more.
However, unless you actually want to allow mutation, I suggest you just make it a genuinely read-only property:
struct T
{
private readonly int u;
public T(int u)
{
this.u = 10;
}
public int U { get { return u; } }
}
Now it's more obvious that you don't want to mutate it even within the struct itself.