How to instantiate a new instance of an object in C #

In VB.Net, I use a variation of this, so when 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 leads to this, but the Tags are null:

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

Is this an acceptable way to create a Tags property while creating a new empty list?

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

Or should I go through this whole ceremony?

 public class SearchModel { private List<TagDetails> _TagDetails; public List<TagDetails> Tags { get { return _TagDetails ?? (_TagDetails = new List<TagDetails>()); } set { _TagDetails = value; } } } 
+4
source share
5 answers

The traditional way is to use the constructor:

 public class SearchModel { public SearchModel() { Tags = new List<TagDetails>(); } public List<TagDetails> Tags { get; set; } } 
+8
source

Create it in the constructor:

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

I did this in C # since you had most of your C # code. You can save an automatic property this way. You can also add an overloaded constructor that uses the list (delete it if you don't want to).

+5
source

The most direct conversion is the following (which does VB backstage):

 public class SearchModel { private List<TagDetails> _Tags = new List<TagDetails>(); public List<TagDetails> Tags { get { return _Tags; } set { _Tags = value; } } } 
0
source

There are also good arguments that they do not reveal a specific list class at all. Of course, I doubt if the setter was wise, you could get the right mess in terms of the lifetime of the object and the garbage collector with this.

 public class SearchModel { private List<TagDetails> _tags; public SearchModel() { _tags = new List<TagDetails>(); } public IEnumerable<TagDetails> Tags {get {return _tags;}} } 

It would be my first attempt, and then add other list type methods that I need, Clear, append, etc.

0
source

If you want to save lazy list creation:

 public class SearchModel { private Lazy<List<TagDetails>> tags = new Lazy(() => new List<TagDetails>()); public List<TagDetails> Tags { get { return this.tags.Value; } } } 

However, with this you cannot set the value.

0
source

Source: https://habr.com/ru/post/1439016/


All Articles