I saw this piece of code somewhere and wondered: when and why would somebody do the following:
doSomething( (MyClass) null );
Have you ever done this? Could you please share your experience?
I saw this piece of code somewhere and wondered: when and why would somebody do the following:
doSomething( (MyClass) null );
Have you ever done this? Could you please share your experience?
If
doSomething
is overloaded, you need to cast the null explicitly toMyClass
so the right overload is chosen:A non-contrived situation where you need to cast is when you call a varargs function:
The last line will produce the following warning:
Let's say you have these two functions, and assume that they accept
null
as a valid value for the second parameters.void ShowMessage(String msg, Control parent);
void ShowMessage(String msg, MyDelegate callBack);
These two methods differ only by the type of their second parameters. If you want to use one of them with a
null
as the second parameter, you must cast thenull
to the type of second argument of the corresponding function, so that compiler can decide which function to call.To call the first function:
ShowMessage("Test", (Control) null);
For the second:
ShowMessage("Test2", (MyDelegate) null);