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
nulltypebbecause it's value typetypeareference type) call made applicable one. - otherwise depends on relationship between
typea,typeb.- if there implicit conversion
typeatypebno implicit conversiontypebtypeaoverload usingtypeaused. - if there implicit conversion
typebtypeano implicit conversiontypeatypeboverload usingtypebused. - otherwise, call ambiguous , fail compile.
- if there implicit conversion
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
Post a Comment