Monday, January 30, 2012

How to create a generic list with anonymous types in C# 3.X

What?

How to create a generic list with anonymous types in C# 3.X

Why?

Anonymous Types is a new feature that is introduced with C# 3.0
Anonymous types are particularly useful when querying and transforming data with LINQ.

So what’s the difference between a normal type and an anonymous type?
First and most important: the anonymous type has no type name.

In C# 2.0 and earlier, we had to give every type a name explicitly.

For example,
class Person
{
    private StringBuilder _personData;
    public StringBuilder PersonData
    {
        get
        {
            return _personData;
        }
        set
        { _personData = value; }
    }

    private String _personName;
    public String PersonName
    {
        get { return _personName; }
        set { _personName = value; }
    }
}

In C# 3.X, we can use automatic properties and write the following:
class Person
{
    public StringBuilder PersonData
    {
        get; set;
    }

    public String PersonName
    {
        get; set;
    }
}

Even better, in C# 3.X, we can use anonymous types and write the following:
var person = new Person { PersonData = new StringBuilder(), PersonName = String.Empty };
So far so good.



How?

How to create a generic list of anonymous types given a single instance of an anonymous type?

Creating a given list of types is easy.
List<Person> persons = new List<Person>();
persons.Add(new Person{ PersonData = new StringBuilder(), PersonName = String.Empty });
So how to create a generic list with anonymous types?

Using a "list factory", this is possible.
var Person = new { PersonData = new StringBuilder(), PersonName = String.Empty };
var persons = MakeList(Person);

persons.Add(new { PersonData = new StringBuilder(), PersonName = "Chaitu" });
persons.Add(new { PersonData = new StringBuilder(), PersonName = "Scott" });

public static List<T> MakeList<T>(T itemOftype)
{
   List<T> newList = new List<T>();
   return newList;
}

No comments:

Post a Comment