Why should member variables be initialized in constructors?

When I first started working with object-oriented programming languages, I was offered the following rule:

When declaring a field in a class, do not initialize it yet. Do it in the constructor.

Example in C #:

public class Test
{
    private List<String> l;

    public Test()
    {
        l = new List<String>();
    }
}

But when someone recently asked me why to do this, I could not think of a reason. I am not very familiar with the internal workings of C # (or other programming languages, since, in my opinion, this can be done in all OO languages).

So why is this done? Is it safety? Properties?

+5
source share
6 answers
  • ,

  • , , . , , , .

+14

# , , . :

class Test
{
    Object o = new Object();
}

:

class Test
{
    Object o;

    public Test()
    {
        this.o = new Object();
    }
}

, , #, , , . , -: .

+10

, , , . , . (1) TDD/Unit . , , , . (2) # 3.0 . , , . , . , #.

Ex. ( 2)

  var foo = new Foo { Bar = "baz" };

  public class Foo
  {
       public string Bar { get; set; }

       public Foo() { }
  }
+2

, . ,

+1

. , . C-, 75% . , , , . Michael comment , , , , . , , .

0

factory , - . , , , , , ... , - , , ( , ).

, , .

0

All Articles