Say I have two overloaded versions of a C# method:
void Method( TypeA a ) { } void Method( TypeB b ) { }
I call the method with:
Method( null );
Which overload of the method is called? What can I do to ensure that a particular overload is called?
It depends on
TypeAandTypeB.nulltoTypeBbecause it’s a value type butTypeAis a reference type) then the call will be made to the applicable one.TypeAandTypeB.TypeAtoTypeBbut no implicit conversion fromTypeBtoTypeAthen the overload usingTypeAwill be used.TypeBtoTypeAbut no implicit conversion fromTypeAtoTypeBthen the overload usingTypeBwill be used.See section 7.4.3.4 of the C# 3.0 spec for the detailed rules.
Here’s an example of it not being ambiguous. Here
TypeBderives fromTypeA, which means there’s an implicit conversion fromTypeBtoTypeA, but not vice versa. Thus the overload usingTypeBis used:In general, even in the face of an otherwise-ambiguous call, to ensure that a particular overload is used, just cast:
or
Note that if this involves inheritance in the declaring classes (i.e. one class is overloading a method declared by its base class) you’re into a whole other problem, and you need to cast the target of the method rather than the argument.