C# 2.0 Delegate bug

July 28, 2006

In C# 2.0 a method does not have to exactly match the delegate signature. Instead, it is legal to use a sub/super type. However, C# fails to handle ValueTypes correctly. In the code below, M5 should work with DSig if they box the int return type, and M6 should work VTSig if the box the int parameter. But they fail to do it, which means that ValueType is not really a subtype of object, but just a bad hack for primitives to make them appear to be a proper subtype. Check out the code:

public delegate object DSig(string x);
public delegate object VTSig (int x) ;
public class Test
{
     public static object M1(string x) { return x; }
     public static object M2(object x) { return x; }
     public static string M3(string x) { return x; }
     public static string M4(object x) { return x.ToString(); }
     public static int M5(string x) { return 4; }
     public static object M6(object x) { return x; }

     static void Main() {
          DSig d1 = M1;
          DSig d2 = M2;
          DSig d3 = M3;
          DSig d4 = M4;

          // Both of these fail because C# won't coerce ValueTypes to objects
          //DSig d5 = M5;
          //VTSig d6 = M6;
     }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: