开发者

Do I need two new List<ParentDetail>() constructors?

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?


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.


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


How about this

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

Excellent explanation Here


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜