Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you define a 'new' property using short hand?

Tags:

c#

vb.net

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'

like image 409
baileyswalk Avatar asked Dec 15 '22 10:12

baileyswalk


2 Answers

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; }
}
like image 67
Darin Dimitrov Avatar answered Dec 26 '22 19:12

Darin Dimitrov


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.

like image 41
qJake Avatar answered Dec 26 '22 18:12

qJake