Consider the following code snippet
namespace ConsoleApplication1
{
public delegate TResult Function<in T, out TResult>(T args);
class Program
{
static void Main(string[] args)
{
Program pg =new Program();
Function<Object, DerivedClass> fn1 = null;
Function<String, BaseClass> fn2 = null;
fn1 = new Function<object, DerivedClass>(pg.myCheckFuntion)
fn2=fn1;
fn2("");// calls myCheckFuntion(Object a)
pg.myCheckFuntion("Hello"); //calls myCheckFuntion(String a)
}
public DerivedClass myCheckFuntion(Object a)
{
return new DerivedClass();
}
public DerivedClass myCheckFuntion(String a)
{
return new DerivedClass();
}
}
why the delegate call and normal method invocation call different methods.
The delegate is bound to
myCheckFuntion(Object)at compile time – you’re telling it to find a method which accepts anObject. That binding is just to a single method – it doesn’t perform overload resolution at execution time based on the actual argument type.When you call
pg.myCheckFuntion("Hello")that will bind tomyCheckFuntion(String)at compile-time because"Hello"is a string, and the conversion from string to string is preferred over the conversion from string to object in overload resolution.Note that if you write:
then that will call
myCheckFuntion(Object).