Every now and they I run into something that makes me wish C# was more dynamic. Today’s example is playing with delegates. For instance the following works:
public void Test()
{
Func<object> blah = Blah;
blah();
}
public string Blah()
{
return string.Empty;
}
This is valid because the return type of the method is always more restrictive than that of the delegate (that is it is covariant). Unfortunately this breaks down with delegate assignment:
public void Test()
{
Func<string> blah1 = Blah;
Func<object> blah2 = blah1;
blah2();
}
public string Blah()
{
return string.Empty;
}
The above does not compile because the compiler cannot do an implicit conversion from Func<string> to Func<object>, nor does it allow an explicit cast. This is somewhat annoying because you could validly substitute a method that returns string for one that returns object provided the new method has a contravariant parameter list.