Overload resolution in C # 4.0 using dynamic types

I do not have access to preview C # 4.0. But I'm curious what the C # 4.0 runtime does when invoking an overloaded method in the following case. Does it solve general overload ... or 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 ) ); } 
+4
source share
1 answer

Sam Ng has an excellent series of blog posts about this. I forget the exact details (and they can still change before the release), but this blog series goes through quite a lot, including generics.

In general, I understand that the result should (if possible) be the same as the result if you only compiled the same code with dynamic expressions, replaced by expressions of the type that the dynamic value has at runtime. (Statically known types are stored in call site information.)

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

 Bar(int) says: 0 

However, looking at it again (and checking which bit is actually dynamic), I'm a little confused. I think this is one of those situations where I will need to study the specification very carefully in order to understand what the correct behavior is. Unfortunately, I do not know when the C # 4.0 specification will be available.

This is hard to understand, and I suspect that the key part is that, at run time, the binder can decide that the value is of type T for the same T as the receiver, and not of type int . Since the receiver is dynamic in this case, the compiler does not perform any overload resolution at all. Hm. Difficult, definitely.

+6
source

Source: https://habr.com/ru/post/1286142/


All Articles