0

I have the following class called Parent. It contains a list of ParentDetail classes:

public class Parent
{

    public Parent()
    {
       this._parentDetails = new List<ParentDetail>();
    }

    public IList<ParentDetail> ParentDetails
    {
        get { return _parentDetails; }
    }

    private List<ParentDetail> _parentDetails = new List<ParentDetail>();

}

public class ParentDetail
{
    public string FileName { get; set; }
}

The class seems to work but I don't understand why "= new List();" appears twice. Can someone explain in a couple of lines what is happening?

Suman Banerjee
  • 1,923
  • 4
  • 24
  • 40
JonAndMarie
  • 223
  • 1
  • 3
  • 7

5 Answers5

1

Do I need two new List() constructors?

No, one of them would be enough - creating two instaces of which one will never be used is superfluous.

Matthias
  • 12,053
  • 4
  • 49
  • 91
1

This is redundancy, which is not needed. Either one of them can be removed.

Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95
0

It doesn't have to, and shouldn't. In this case _parentDetails is initialised twice.

Both the assignments are equivalent in this case. For what it's worth I prefer initiailising in the default constructor, not the field/member declaration.

Kieren Johnstone
  • 41,277
  • 16
  • 94
  • 144
0

How about this

private List<ParentDetail> _parentDetails;
public Parent()
{
   this._parentDetails = new List<ParentDetail>();
}

Excellent explanation Here

Community
  • 1
  • 1
V4Vendetta
  • 37,194
  • 9
  • 78
  • 82
0

I dont think the inline creation of new List<ParentDetail>(); is needed as it is already done inside your constructor..Or else you can remove the constructor as a whole...

The inline code when compiled creates a default constructor and moves that piece of code inside the constructor.

Ashley John
  • 2,379
  • 2
  • 21
  • 36