Property Delegates with Anonymous Methods


No programming language is perfect. In spite of the many strengths of C#, there are still a few gaping holes, including generics variance and property delegates.

A delegate is a reference to a method. Unfortunately, C# currently does not support property delegates, in other words, a reference to a property. But there are a few workarounds, one of which involves anonymous methods.

An anonymous method is a new feature in C# 2.0 that enables you to define an anonymous (nameless) method called by a delegate. Anonymous methods are perfect when there is no need for multiple targets, and the code is relatively short and simple. They also come in handy when you need a delegate to a property.

Read the rest of this entry »

Convert Between Generic IEnumerable


Generics in .NET 2.0 provides the ability to create strongly-typed collections in C#. Unfortunately, C# currently does not support generics variance, which would allow inheritance of generic types.

For example, consider a list of strings and a list of objects:

List<string> strings = new List<string>();
strings.Add( "hello" );
strings.Add( "goodbye" );
List<object> objects = new List<object>();
objects.AddRange( strings );

The final line in the code above generates a compiler error. But why? Since the ‘string’ class derives from the ‘object’ class, one would expect List<string> to also implicitly derive from List<object>. This capability is called generics variance, but C# currently does not support it.

Fortunately, you can brute force your way to a solution by creating a generic ConvertIEnumerable method:

Read the rest of this entry »