Initialize a List<T> with inline definition of <T>

  • A+
Category:Languages

You can always define a class like this:

public class item {   int id;   string name; } 

and then use it like this:

List<item> items = new List<item>(); 

Can we not do something like this:

var items = new List<{int id, string name}>(); 

Just a short way of initializing when underlying object definition is simple and predictable.

This is possible in JavaScript (I have seen examples in Angular).

Sorry if this is answered before, my quick search could not find an answer to this specific topic on Google or SO.

 


C# 7 introduces tuples, so you can do this:

var list = new List<(int id, string name)>(); list.Add((3, "Bob"));  var (id, name) = list[0];  var entry = list[0]; string s = $"{entry.name} has ID {entry.id}";  foreach (var (id, name) in list) {  } 

Before C# 7 you can use the old Tuple type, which is a bit more messy:

var list = new List<Tuple<int, string>>(); list.Add(Tuple.Create(3, "Bob"));  foreach (var item in list) {     int id = item.Item1;     string name = item.Item2; } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: