c# - delegate covariance and Contavariance -
consider 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 delegate call , normal method invocation call different methods.
the delegate bound mycheckfuntion(object)
@ compile time - you're telling find method accepts object
. binding single method - doesn't perform overload resolution @ execution time based on actual argument type.
when call pg.mycheckfuntion("hello")
that bind mycheckfuntion(string)
@ compile-time because "hello"
string, , conversion string string preferred on conversion string object in overload resolution.
note if write:
object text = "hello"; pg.mycheckfuntion(text);
then that call mycheckfuntion(object)
.
Comments
Post a Comment