mercredi 2 septembre 2015

Reflection and dynamic method resolution

It is safe to assume that when calling a method via reflection (or using dynamic) the most specific one is selected, as in ordinary code?

Let's consider this code:

public class Animal {}
public class Dog : Animal {}

public class MyClass
{
    public void SayHello(Dog animal)
    {
        Console.WriteLine("Hello dog!");
    }

    public void SayHello(Animal animal)
    {
        Console.WriteLine("Hello animal!");
    }
}

When calling it with:

var myClass = new MyClass();

// Classic invocation
myClass.SayHello(new Dog());

// Reflection
var method = myClass.GetType().GetMethod("SayHello", new[] { typeof(Dog) });
method.Invoke(myClass, new object[] { new Dog() });

// dynamic
((dynamic)myClass).SayHello((dynamic)new Dog());

When calling SayHello is the correct method invoked using the classic method resolution? In other words the output will be always "Hello dog!"?

From a quick test the answer seems to be yes, but I cannot find any specific documentation on MSDN.





Aucun commentaire:

Enregistrer un commentaire