Home > Development > Anonymous Types and Generics

Anonymous Types and Generics


Trying to use anonymous type with Generics is just a pain. Going to download VS 2010 and see if the dynmaic type helps.

Check this code out. Its a major headache….

using System;
using System.Collections.Generic;


namespace AnonymousTypesAndCollections
{


    class Program
    {
        static void Main(string[] args)
        {
            var customer = new
                               {
                                   Id = 1,
                                   Name = "Blair Davidson"
                               };

            Type openGenericType = typeof(List<>);
            Type closedGenericType = openGenericType.MakeGenericType(customer.GetType());

            object list = Activator.CreateInstance(closedGenericType);

            closedGenericType.GetMethod("Add").Invoke(list, new[] {customer});
            Console.WriteLine("Count: {0}",closedGenericType.GetProperty("Count").GetGetMethod().Invoke(list,null));

            Console.WriteLine(closedGenericType.FullName);
            Console.ReadKey();
        }
    }
}

Anyone know another way to do this?

Advertisements
Categories: Development Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: