After this evening's Northwest Ohio .NET User
Group meeting, Jason Follas and
I met up at Tony Packo's for a bit of post-meeting
hangtime. In our conversation, Jason admitted his frustration at not being able
to write code like this using C# generics:
using System;
using System.Collections.Generic;
static class Program
{
static void
DoSomethingWithList(List<> list) { }
static void
Main(string[] args)
{
List<string> stringList =
new List<string>();
List<int> intList =
new List<int>();
DoSomethingWithList(stringList);
DoSomethingWithList(intList);
}
}
Unfortunately, that code doesn't compile. The problem is that List<> has to have
its "T" type parameter filled in. To solve this dilemma, make "DoSomethingWithList"
a generic method like this:
static void
DoSomethingWithList<T>(List<T> list) { }
Now, the list parameter will be of type List<T> where T is filled in when the
DoSomethingWithList method is called. Hence, we can write code like this:
List<string>
stringList = new List<string>();
List<int> intList
= new List<int>();
DoSomethingWithList<string>(stringList);
DoSomethingWithList<int>(intList);
IMO, the calling code isn't very elegant with the angle brackets added to DoSomethingWithList.
Fortunately, the C# compiler will infer the actual types of generic type parameters
if you don't fill them in. I'm currently working on an article that explores this
feature in detail because I don't see many people using it and, frankly, it is a
life saver for cleaning unwanted angle-brackets out of perfectly readable code.
Here is the code again using compiler inference:
using System;
using System.Collections.Generic;
static class
Program
{
static void
DoSomethingWithList<T>(List<T> list) { }
static void
Main(string[]
args)
{
List<string>
stringList = new List<string>();
List<int> intList
= new List<int>();
DoSomethingWithList(stringList);
DoSomethingWithList(intList);
}
}