Alex Rivera | Logout

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

Asked 2009-04-05T19:42:03.947
40

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?

Edit
Report

1 Answer

8

Jon Skeet has given a comprehensive answer, but from a design point of view you shouldn't depend on corner-cases of the compiler specification. If nothing else, if you have to look up what it does before you write it, the next person to try to read it won't know what it does either. It's not maintainable.

Overloads are there for convenience, and two different overloads with the same name should do the same thing. If the two methods do different things, rename one or both of them.

It's more usual for an overloaded method to have variants with varying numbers of parameters, and for the overload with less parameters to supply sensible defaults.

e.g. string ToString(string format, System.IFormatProvider provider) has the most parameters,
string ToString(System.IFormatProvider provider) supplies a default format, and
string ToString() supplies a default format and provider,

answered 2009-04-05T20:26:21.377

Your Answer