Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between this initialization methods?

Tags:

c#

.net

What is the difference between this two codes?

class SomeClass   
{   

   SomeType val = new SomeType();   

}   

and

class SomeClass  
{      
   SomeType val;   

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

}   

Which method is preferd?

like image 563
Samvel Siradeghyan Avatar asked Mar 19 '10 06:03

Samvel Siradeghyan


1 Answers

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.

like image 129
Fredrik Mörk Avatar answered Sep 17 '22 09:09

Fredrik Mörk