Variable Declaration - Best Practices

I found some time ago (and I want to confirm again) that if you declare a class level variable, you should not call its constructor until you call the constructor or load the class. The reason was performance - but are there other reasons to do this or not? Are there exceptions to this rule?

, that is: this is what I do based on what I consider to be best practice:

public class SomeClass
{
   private PersonObject _person;

   public SomeClass()
   {
      _person = new PersonObject("Smitface");
   }
}

opposite:

public class SomeClass
{
   private PersonObject _person = new PersonObject("Smitface");

   public SomeClass()
   {

   }
}
+5
source share
12 answers

, (handeling). , , - . .

Nescio , , - .

Option # 1.

+12

, IL, , , - , .

, . , , " " .

+6

, , , , , , ( .. , , ).

, .

, , , , , , , , , .

+4

" " " " (IOC), "" (, DAL) , (furthur )

, ctor,

SomeClass
{
   private PersonObject per;

 public SomeClass(PersonObject person) 

 {      
     per = person;   
 }   

}

private PersonObject Joe = new PersonObject ( "Smitface" );

SomeClass MyObj = SomeClass (Joe);

, , DAL DAL unit test...

+2

. , readonly , . , , , , .

+1

. . , . , .

, , in-constructor ( discorax).

+1

, , .

, .

0

. , . - , .

0

, , , , .

, , .

0

, .. ,

0

, , , . , . .

0

, () .

: , , , , . , , .

, , , .

-3

All Articles