I have had some interesting conversations over the last week or so about generics. It was brought up out of a MCTS study group and then in the internal DNUG that I lead. so let me break it down.
Without Generics -
I have to setup collections of objects manual and for each type that I want to use. To add, sort, filter, or aggregate this collection takes a lot of code and time. Some things like ArrayList return objects which means all that casting or reflection over head to get into the objects I need.
With Generics -
I have to setup a collection and give it the input types. It handles sorting, filtering, adding, and aggregates through the use of generic Action<T>, Func<T>, or Predicate<T>. I can write sorts and filters and make them generic so that I don?t have to copy/paste change type.
Generics are not the end all and be all but they help a great deal when you are trying not to repeat yourself. I have found that when using generics that the compiler actually spits out the methods with the implemented types in them, which means that generics while great are syntactic sugar, and I have a sweet tooth.
With Linq being based on the use of IEnumerable<T> and the new parallel extensions to .NET 4.0 being able to spread the workload of Action<T> and Task<T> across multiple processors I would tell everyone. Start learning generics. It is easy to use once you wrap your head around it. Like if I wanted to add two numbers of different types I could write this:
public float Add(int one, decimal two)
{
float item = new float();
item = float.Parse(one.ToString()) + float.Parse(two.ToString());
return item;
}
public float Add(decimal one, decimal two)
{
float item = new float();
item = float.Parse(one.ToString()) + float.Parse(two.ToString());
return item;
}
public float Add(int one, int two)
{
float item = new float();
item = float.Parse(one.ToString()) + float.Parse(two.ToString());
return item;
}
public float Add(double one, double two)
{
float item = new float();
item = float.Parse(one.ToString()) + float.Parse(two.ToString());
return item;
}
public float Add(int one, double two)
{
float item = new float();
item = float.Parse(one.ToString()) + float.Parse(two.ToString());
return item;
}
public float Add(double one, decimal two)
{
float item = new float();
item = float.Parse(one.ToString()) + float.Parse(two.ToString());
return item;
}
or I could write this:
public float Add<T, T2>(T one, T2 two)
{
return float.Parse(one.ToString()) + float.Parse(two.ToString());
}
Which would you prefer?
Enjoy, and remember.
Code Like you have to support it.
f5777388-7383-421d-be15-6022886684ae|0|.0