C#: Passing null to overloaded method - which method is called? -


say have 2 overloaded versions of c# method:

void method( typea ) { } void method( typeb b ) { } 

i call method with:

method( null ); 

which overload of method called? can ensure particular overload called?

it depends on typea , typeb.

  • if 1 of them applicable (e.g. there no conversion null typeb because it's value type typea reference type) call made applicable one.
  • otherwise depends on relationship between typea , typeb.
    • if there implicit conversion typea typeb no implicit conversion typeb typea overload using typea used.
    • if there implicit conversion typeb typea no implicit conversion typea typeb overload using typeb used.
    • otherwise, call ambiguous , fail compile.

see section 7.4.3.4 of c# 3.0 spec detailed rules.

here's example of not being ambiguous. here typeb derives typea, means there's implicit conversion typeb typea, not vice versa. overload using typeb used:

using system;  class typea {} class typeb : typea {}  class program {     static void foo(typea x)     {         console.writeline("foo(typea)");     }      static void foo(typeb x)     {         console.writeline("foo(typeb)");     }      static void main()     {         foo(null); // prints foo(typeb)     } } 

in general, in face of otherwise-ambiguous call, ensure particular overload used, cast:

foo((typea) null); 

or

foo((typeb) null); 

note if involves inheritance in declaring classes (i.e. 1 class overloading method declared base class) you're whole other problem, , need cast target of method rather argument.


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

python - pip wont install .WHL files -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -