What is the difference between these initialization methods?

What is the difference between these two codes?

class SomeClass   
{   

   SomeType val = new SomeType();   

}   

and

class SomeClass  
{      
   SomeType val;   

   SomeClass()   
   {   
       val = new SomeType();   
   }   

}   

Which method prefers?

+5
source share
2 answers

There is almost no difference between them. Field assignment will occur inside the constructor in both cases. However, there is a difference in how this happens with respect to base class constructors. 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 constructor of the base class will be called after the field is assigned in the class One, but before the assignment in the class Two.

+7
source

In the first version, you can define several constructors without thinking about the mark = new SomeType()in each of them.

+2

All Articles