Can you define a “new” property using a short hand?

I recently converted a fair bit of code from VB to C #, and I noticed that in VB you can initiate a new obj using shorthand, is this possible in C # or you need to use a background field.

Public Property MyList As New List(Of String) 

It seems like the C # equivalent:

 private List<String> _myList = new List<string>(); public List<String> MyList { get { return _myList; } set { _myList = value; } } 

Note * The pain of writing this out can be made much simpler using the shortcut 'propfull' command

+4
source share
3 answers

You cannot create a property in C # and initialize it at the same time. You can only do this with fields.

This is valid, but will not initialize the value ( MyList will be null ):

 public List<string> MyList { get; set; } 

This is valid (but this is a field, not a property):

 public List<string> MyList = new List<string>(); 

This is not :

 public List<string> MyList { get; set; } = new List<string>(); 

It is customary to create properties inside classes and then initialize them inside the constructor of this class.


Update: Now this is valid syntax in C # 6.0 .

+5
source

C # equivalent?

C # also supports auto-implemented properties , which does not require a support field, but does not automatically assign a value to this property:

 public List<string> MyList { get; set; } 

The compiler issues an appropriate support field. You can also specify various access modifiers for your recipient and setter:

 public List<string> MyList { get; private set; } 

And if you want to instantiate the property at the same time using this auto property, then no, that’s not possible, but you can do it in the constructor of the class:

 public class MyClass { public MyClass() { this.MyList = new List<string>(); } public List<string> MyList { get; set; } } 
+8
source

In C # just do:

 public List<string> MyList { get; set; } 
-1
source

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


All Articles