Question

I don't have access to the C# 4.0 preview yet. But I am curious, what does the C# 4.0 runtime do when invoking an overloaded method in the following case. Does it resolve to the generic overload ... or the specialized overload.

public class Foo<T>
{
  protected string BarImpl( T value ) { return "Bar(T) says: " + value.ToString(); }

  protected string BarImpl( int value ) { return "Bar(int) says: " + value.ToString(); }

  public string Bar( T value )
  {
    dynamic foo = this;
    return foo.BarImpl( value );
  }
}

public static void Main( string args[] )
{
  var f = new Foo<int>();

  Console.WriteLine( f.Bar( 0 ) );
}
Was it helpful?

Solution

In general, my understanding that the result should (whenever possible) be the same as the result would be if you compiled the same code with just the dynamic expressions replaced by expressions of the type that the dynamic value has at execution time. (Statically-known types are preserved in the call site info.)

In this particular case, having just your code with .NET 4.0b1, the result is:

Bar(int) says: 0

However, having looked at this again (and checked which bit is actually dynamic) I'm slightly confused. I think it's one of those situations where I'd have to look very carefully at the spec to understand what the correct behaviour is. Unfortunately I don't know when the C# 4.0 spec will be available.

It's a tricky one to reason about, and I suspect the key part is whether at execution time the binder is able to work out that the value is of type T for the same T as the receiver, rather than type int. Because the receiver is dynamic in this case, the compiler doesn't do any overload resolution at all. Hmm. Tricky one, definitely.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top