Why is it possible to instantiate a struct without the new keyword?

前端 未结 7 1817
夕颜
夕颜 2020-12-07 15:29

Why are we not forced to instantiate a struct, like when using a class?

7条回答
  •  不思量自难忘°
    2020-12-07 15:43

    Because a struct is a value-type. When you declare a variable of it, the instance is immediateley there.

    A constructor (the new operator) is therefore optional for a struct.

    Consider

    struct V { public int x; }
    class  R { public int y = 0; }
    
    void F() 
    {
       V a;   // a is an instance of V, a.x is unassigned  
       R b;   // b is a reference to an R
    
       a.x = 1; // OK, the instance exists
     //b.y = 2; // error, there is no instance yet
    
       a = new V();  // overwrites the memory of 'a'. a.x == 0
       b = new R();  // allocates new memory on the Heap
    
       b.y = 2; // now this is OK, b points to an instance
    }
    

提交回复
热议问题