Is it possible to initialize the Inferred List?

I know that I can initialize the collection as follows

var array = []{"1", "2", "3"}; 

which will automatically establish that I want to create an array of type String, but this will limit me to adding or removing indexes from the array, since the array has a fixed size.

Is there a way to do the same with the Generic List type, and the compiler should conclude which type β€œT” is based on the elements of the initializer?

Perhaps something like the new List () {...}

+4
source share
4 answers
 var list = new[] {"1", "2", "3"}.ToList(); 
0
source

No, this is not supported - you must specify a type parameter, but you can use collection initializers .

 var list = new List<String> { "1", "2", "3" }; 

However, you could create a helper method

 public static class ListUtilities { public static List<T> New<T>(params T[] items) { return new List<T>(items); } } 

and use it like that.

 var list = ListUtilities.New("1", "2", "3"); 

But it's probably not worth it; you get nothing, if anything. And first, it will create an array, and it will be used to populate the list. So this is not so different from Keith Nicholas var list = new[] { "1", "2", "3" }.ToList(); .

+3
source

Here is a pretty great example:

 static void Main(string[] args) { var Customer = new { FirstName = "John", LastName = "Doe" }; var customerList = MakeList(Customer); customerList.Add(new { FirstName = "Bill", LastName = "Smith" }); } public static List<T> MakeList<T>(T itemOftype) { List<T> newList = new List<T>(); return newList; } 

http://kirillosenkov.blogspot.com/2008/01/how-to-create-generic-list-of-anonymous.html

+2
source

Yes. But no conclusions.

 var li = new List<int> {1,2,3,4,5,6}; 

The closest you get

 var li = new List<dynamic> {1,2,3,4,5} 
0
source

All Articles