tags:

views:

67

answers:

1

C#: can you instantiate objects via a Property setter?

eg.

private List<MyObject> myList;
public List<MyObject> MyListProperty { get {return myList;} set {myList = value;} }

THEN:

MyListProperty = new List<MyObject>();
+5  A: 

Yes, that is perfectly valid.
In the line MyListProperty = new List<MyObject>(); you do not "instantiate objects via a Property setter". First, you instantiate a new list, and then you set MyListProperty to the list you've created. It is equivalent to:

List<MyObject> myObjectList = new List<MyObject>();
MyListProperty = myObjectList;

Next, if you want your code to compile you should specify the type of your property:

public List<MyObject> MyListProperty
{
     get {return myList;}
     set {myList = value;}
}
Kobi