Why Must I Initialize All Fields in my C# struct with a Non-Default Constructor?

前端 未结 6 692
自闭症患者
自闭症患者 2020-12-08 23:27

I would like to try this code:

public struct Direction
{
   private int _azimuth;

   public int Azimuth
   {
     get { return _azimuth; }
     set { _azimu         


        
6条回答
  •  一整个雨季
    2020-12-08 23:45

    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.

    new BimonthlyPairStruct()
    

    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

提交回复
热议问题