Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate a new instance of a property in C#

Tags:

c#

vb.net

In VB.Net I am using a variation of this so when a the SearchModel is used there is an empty list of Tags ready to go.

Public Class SearchModel
    Public Property Tags As New List(Of TagDetails)
End Class 

A simple conversion results in this but "Tags" is null:

public class SearchModel
{
    public List<TagDetails> Tags { get; set; }
}

Is this an acceptable way to create the "Tags" property and create a new empty list at the same time?

public class SearchModel
{
    public List<TagDetails> Tags = new List<TagDetails>();
}

Or should I go through all of this ceremony?

public class SearchModel
{
  private List<TagDetails> _TagDetails;
    public List<TagDetails> Tags
    {
        get { return _TagDetails ?? (_TagDetails = new List<TagDetails>()); }
        set { _TagDetails = value; }
    }
}
like image 928
ericdc Avatar asked Dec 12 '22 21:12

ericdc


1 Answers

The conventional way is using a constructor:

public class SearchModel
{
    public SearchModel()
    {
        Tags = new List<TagDetails>();
    }
    public List<TagDetails> Tags { get; set; }
}
like image 122
Tim Schmelter Avatar answered Dec 14 '22 11:12

Tim Schmelter