What is the difference between this initialization methods?

后端 未结 2 1296
再見小時候
再見小時候 2021-01-18 21:54

What is the difference between this two codes?

class SomeClass   
{   

   SomeType val = new SomeType();   

}   

and

<         


        
相关标签:
2条回答
  • 2021-01-18 22:30

    There is almost not difference between them. The assignment of the field will happen within the constructor in both cases. There is a difference in how this happpens in relation to base class constructors though. Take the following code:

    class Base
    {
        public Base()
        {
    
        }
    }
    
    class One : Base
    {
        string test = "text";
    }
    
    class Two : Base
    {
        string test;
        public Two()
        {
            test = "text";
        }
    }
    

    In this case the base class constructor will be invoked after the field assignment in the class One, but before the assignment in class Two.

    0 讨论(0)
  • 2021-01-18 22:36

    The first version allows you to define multiple constructors without having to remember to put the = new SomeType() in each one.

    0 讨论(0)
提交回复
热议问题