CJ7
CJ7

Reputation: 23295

Can you instantiate objects via a Property setter?

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>();

Upvotes: 3

Views: 290

Answers (1)

Kobi
Kobi

Reputation: 138127

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;}
}

Upvotes: 5

Related Questions