Archive

Posts Tagged ‘Anonymous Types’

Tuples C#

July 14, 2010 Leave a comment

Provide a way to group data items together. For example you may want a data item with a persons id and name.
A tuple provides a convenient way to do so. It is also benefical over anonymous types if you need to use it outside the current function scope.

Se the following example.

using System;

namespace Tuples
{
    class Program
    {
        static void Main(string[] args)
        {
            Tuple<int, string> t1 = new Tuple<int, string>(1,"Blair Davidson");
            Tuple<int, String> t2 = Tuple.Create(2, "Chia Ling");

            Console.WriteLine(t1.Item1 + " " + t1.Item2);

        }
    }
}

Blair…

Advertisements

.NET 4 Dynamic Types with Anonymous Types

March 6, 2010 Leave a comment

A post i wrote a while ago on pain with anonymous types has been totally rectified with the use of dynamic. How cool is the following code 🙂

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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

            List<dynamic> list = new List<dynamic> {customer};

            Console.WriteLine("Count: {0}", list.Count);

            Console.WriteLine(list.GetType().FullName);
            Console.ReadKey();
        }
    }
}

Not sure where I will use this yet but i will help work around a some hard issues im sure 🙂

Blair…

Anonymous Types and Generics

February 11, 2010 Leave a comment

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?

Categories: Development Tags: , , ,