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:
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:
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:
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:
Page rendered at Thursday, November 20, 2008 6:12:36 PM (Eastern Standard Time, UTC-05:00)