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

前端 未结 6 705
自闭症患者
自闭症患者 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:43

    I just found an explanation in the MSDN forum stating that this rule is enforced because zeroing out the memory is skipped if you use a none default constructor. So you will have to provide initialization values for all fields in order to avoid some fields containing random values. You achieve this easily be calling the parameter less default constructor, but at the cost of initializing some fields twice.

    I cannot tell if this explanation is correct, but it sounds reasonable.

    When you define a non-default initializer, C# requires you to set all fields because it skips the zeroing of memory and lets you initialize it - otherwise you'd have to have a double initialization performance hit. If you don't care about the (very slight) performance hit you can always chain a call to the : this() initializer and then only initialize selected fields.

提交回复
热议问题