Tuesday, May 03, 2005

.NET 2.0 Generics

I am testing out the new .NET 2.0 Generics feature, and found it's very cool.

Generics allow you to define type-safe classes without compromising type safety, performance, or productivity (From MSDN). That's really true especially on productivity. With Generics you are no longer need to do the type casting. Goodbye ArrayList because we have generic List!
using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
public interface ITimeable
{
DateTime GetTime();
}

public class MyEvent : ITimeable
{
private string _name;
private DateTime _time;
public MyEvent(string name, DateTime time)
{
_name = name;
_time = time;
}
public DateTime GetTime()
{
return _time;
}
public override string ToString()
{
return _name;
}
}

public class Helper
{
public static List<T> GenericSortByTime<T>(List<T> items) where T : ITimeable
{
items.Sort(delegate(T item1, T item2)
{
return item1.GetTime().CompareTo(item2.GetTime());
});
return items;
}

public static List<T> GenericSortByName<T>(List<T> items) where T : class
{
items.Sort(delegate(T item1, T item2)
{
return item1.ToString().CompareTo(item2.ToString());
});
return items;
}
}

class Program
{
static void Main(string[] args)
{
DateTime now = DateTime.Now;
List<MyEvent> events = new List<MyEvent>();
events.Add(new MyEvent("1", now.AddDays(1)));
events.Add(new MyEvent("3", now.AddDays(2)));
events.Add(new MyEvent("2", now.AddDays(3)));
events.Add(new MyEvent("a", now.AddDays(-1)));
events.Add(new MyEvent("b", now.AddDays(-2)));
Console.WriteLine("Original list:");
foreach (MyEvent myEvent in events)
Console.WriteLine(myEvent.ToString() + ":" + myEvent.GetTime().ToString());
events = Helper.GenericSortByTime(events);
Console.WriteLine("Sort by time:");
foreach (MyEvent myEvent in events)
Console.WriteLine(myEvent.ToString() + ":" + myEvent.GetTime().ToString());
events = Helper.GenericSortByName(events);
Console.WriteLine("Sort by name:");
foreach (MyEvent myEvent in events)
Console.WriteLine(myEvent.ToString() + ":" + myEvent.GetTime().ToString());
Console.Read();
}
}
}

Result: