I have been converting a fair bit of code recently from VB to C# and I have noticed in VB you can initiate a new obj using shorthand, is this possible in C# or do you have to use a backing field.
Public Property MyList As New List(Of String)
It appears that the C# equivalent is:
private List<String> _myList = new List<string>();
public List<String> MyList
{
get { return _myList; }
set { _myList = value; }
}
Note* The pain of writing out this can be made much easier by using the shortcut command 'propfull'
C# equivalent?
C# also supports auto-implemented properties
which doesn't require a backing field but doesn't automatically assign a value to this property:
public List<string> MyList { get; set; }
The compiler will emit the corresponding backing field. You could also specify different access modifiers for your getter and setter:
public List<string> MyList { get; private set; }
And if you wanted to instantiate the property at the same time using this auto property then, no, this is not possible, but you could do it in the constructor of the class:
public class MyClass
{
public MyClass()
{
this.MyList = new List<string>();
}
public List<string> MyList { get; set; }
}
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 it's a field, not a property):
public List<string> MyList = new List<string>();
This is not valid:
public List<string> MyList { get; set; } = new List<string>();
It's common to create properties within classes and then initialize them within the constructor of that class.
Update: This is now valid syntax in C# 6.0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With