1

I would like to add a new item at the back of a list, and get the newly created item.

Let's assume that we could do something like this for one moment:

class Temp
{
    public string First { get;set;}
    public string Second { get;set;}
}
List<string> list = new List<string>();
var newItem = list.Push();
newItem.First="asd";
newItem.Second = "qwe;

this would be easier than

var newItem = new Temp();
newItem.First="asd";
newItem.Second = "qwe;
list.Add(newItem);

especially when I can't use auto-properties.

Is this possible?

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
AndreiM
  • 815
  • 9
  • 17
  • 2
    Makes no sense what you are asking. please be clearer. you can add an item to the back of the list sure by using the Insert method of the List and giving it the index to insert at – Ahmed ilyas Oct 03 '15 at 18:38

2 Answers2

0

You can use object initializers:

var list = new List<Temp>();
list.Add(new Temp{ First = "abc", Second = "def" });

Or together with a collection initializer:

var list = new List<Temp> { new Temp{ First = "abc", Second = "def" } };

This turns your four liner into a one liner.

Or with more than one entry:

var list = new List<Temp> {
    new Temp{ First = "abc", Second = "def" },
    new Temp{ First = "ghi", Second = "jkl" },
    new Temp{ First = "mno", Second = "pqr" }
};

And it should of course be a list of Temp instead of a list of string.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
0

Unless you implement your own List type and add the Push method, the only way you can do that is if the T in List can be constructed using a parameterless constructor.

Here's an extension method for that.

This is not recommended, but is an answer to your question.

Something along the lines of this - I did not compile or run this code

public static class ListEx {
  public static T Push<T>(this List<T> list) where T: new() {
    // Create an instance of T.
    var instance = new T();
    // Add it to the list.
    list.Add(instance);
    // Return the new instance.
    return instance;
  }
}
Jeff
  • 12,085
  • 12
  • 82
  • 152