Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting null as an object?

I came across this code today

AsyncInvoke(OnTimeMessageTimer, (object)null, (ElapsedEventArgs)null);

Is there anything wrong with it or no?

like image 332
sthay Avatar asked Dec 11 '08 00:12

sthay


People also ask

Can null be cast to object?

1 Answer. You can cast null to any source type without preparing any exception. The println method does not throw the null pointer because it first checks whether the object is null or not.

Can null be cast to object Java?

You can cast null to any reference type without getting any exception. The println method does not throw null pointer because it first checks whether the object is null or not. If null then it simply prints the string "null" . Otherwise it will call the toString method of that object.

Is a null an object?

No , null is not an object.It is a reference type and its value does not refer to any object and so there is no representation of null in memory.

Can you cast a null C#?

Since null is a valid value for all reference types, as long as the cast route exists you should be fine.


2 Answers

Sometimes, you need to to this when the method is overloaded... to tell the compiler which one you are calling. A null object is still null and it is safe.

like image 115
Brian Genisio Avatar answered Sep 21 '22 10:09

Brian Genisio


it probably needs the cast to resolve overloads

like image 39
Jimmy Avatar answered Sep 19 '22 10:09

Jimmy