Home > database >  c# add object to list via its constructor
c# add object to list via its constructor

Time:11-06

Just because of interest ...

Given I have a statically defined List<Car> CarsList, and an object of type Car, can I instantiate a new car and add it to the list, while getting a reference to it, in a one-liner?

If I instantiate a car like c1 = new Car("Honda Civic"), it seems I cannot add the car to the list in its constructor:

public Car (string name) {
    _name = name;
    CarsList.add(this);  // adds null
}

And it seems that I can not do it the other way round either:

c1 = CarsList.add(new Car("Honda Civic"));  // does not work, list.add does not return a reference to the newly added object.

Is there any way to achieve what I want?

CodePudding user response:

If I really wanted such a construct, I would add an extension method to List<T> which adds the item to the list and returns the item. I would call that extension method With().

That having been said, adding your Car to the CarsList from within the constructor of Car should not add null. You must be doing something fishy there.

  • Related