Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaration of Anonymous types List [duplicate]

Is there any way to declare a list object of anonymous type. I mean

List<var> someVariable = new List<var>(); someVariable.Add(              new{Name="Krishna",                   Phones = new[] {"555-555-5555", "666-666-6666"}}                 ); 

This is because I need to create a collection at runtime.

like image 525
Krishna Avatar asked Feb 24 '10 16:02

Krishna


People also ask

What keyword do you use to declare an anonymous type?

The anonymous type declaration starts with the new keyword. The declaration initializes a new type that uses only two properties from Product . Using anonymous types causes a smaller amount of data to be returned in the query.

What is the difference between an anonymous type and a regular data type?

The compiler gives them a name although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.

What are difference between anonymous and dynamic types?

Anonymous type is a class type that contain one or more read only properties whereas dynamic can be any type it may be any type integer, string, object or class. Anonymous types are assigned types by the compiler. Anonymous type is directly derived from System.

What are anonymous data types?

Anonymous types are a feature of C# 3.0, Visual Basic . NET 9.0, Oxygene, Scala and Go that allows data types to encapsulate a set of properties into a single object without having to first explicitly define a type. This is an important feature for the SQL-like LINQ feature that is integrated into C# and VB.net.


2 Answers

How about dynamic?

List<dynamic> dynamicList = new List<dynamic>();   dynamicList.Add(new { Name = "Krishna",  Phones = new[] { "555-555-5555", "666-666-6666" } });  
like image 172
Jai Kannah Avatar answered Sep 20 '22 23:09

Jai Kannah


It involves a bit of hackery but it can be done.

static List<T> CreateListFromSingle<T>(T value) {   var list = new List<T>();   list.Add(value);   return list; }  var list = CreateListFromSingle(    new{Name="Krishna",                   Phones = new[] {"555-555-5555", "666-666-6666"}}                 ); 
like image 37
JaredPar Avatar answered Sep 17 '22 23:09

JaredPar