I would like to try this code:
public struct Direction
{
private int _azimuth;
public int Azimuth
{
get { return _azimuth; }
set { _azimuth = value; }
}
public Direction(int azimuth)
{
Azimuth = azimuth
}
}
But it fails on compilation, I understand that struct need to init all its fields.
but i am trying to understand what happens under the CLR\IL hoods.
why it need all the fields before any other method\property\this etc.
Thanks.
Value Types are created on the stack (unless nested within a reference type) There is something about fields/locations on the stack that the CLR can’t guarantee that they will be zeroed out (contrary to fields/locations on the managed heap which are guaranteed to be zeroed out). Hence they must be written to before being read. Otherwise it’s a security hole.
The struct’s default ctor (which takes no parameters and which you’re not allowed to explicitly specify) zeroes out all fields of a struct and hence you can use a struct after you do.
However when you implement your parameterized ctor, you must ensure that all fields have been initialized – which is required for the CLR to pass your code as safe/verified .
See Also: CLR via C# 2nd Ed – Pg 188