4

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'

baileyswalk
  • 1,198
  • 2
  • 17
  • 29
  • 1
    Short answer: No, there is no direct translation from this line into C#, you cannot initialize and define a property on the same line. – qJake May 15 '13 at 15:53
  • This could be a duplicate although it doesn't mention VB.NET: [Initializing C# auto-properties](http://stackoverflow.com/questions/169220/initializing-c-sharp-auto-properties) – Tim Schmelter May 15 '13 at 15:54
  • @TimSchmelter Agreed, but probably shouldn't be closed as a dupe because this question addresses VB to C# migration whereas that one does not. – qJake May 15 '13 at 15:56
  • possible duplicate of [How do you give a C# Auto-Property a default value?](http://stackoverflow.com/questions/40730/how-do-you-give-a-c-sharp-auto-property-a-default-value) – nawfal Jul 17 '14 at 21:17

3 Answers3

8

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; }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
5

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.

qJake
  • 16,821
  • 17
  • 83
  • 135
-1

In C# simply do:

public List<string> MyList { get; set; }
Belogix
  • 8,129
  • 1
  • 27
  • 32