Thursday, May 05, 2005

Difference between java 'null' and C sharp 'null'

In java, when you try to print a null reference, what do U get?

For e.g. Object obj = null;System.out.println(obj);

What gets printed is "null".

So basically a null reference when converted to a string results in "null".
But in Csharp, the same code will print a empty string

Object obj = null;
Console.WriteLine(obj);

Very imp difference for java developers learning C#

Another important difference is while Type-Casting or Boxing/UnBoxing as it is known in C#.Java does not allow us to cast a reference type to a primitive type.So the following code in Java would throw an compilation error:

boolean b = (boolean)getSomeObject();

Assume getSomeObject() method has the signature:
public object getSomeObject()

But in C#, it is possible to type-cast an reference type to an primitive. So the following code would not give a compilation error.

bool b = (bool)getSomeObject();

But at runtime, if getSomeObject() returns a 'null' , then we would get a 'NullReferenceException'
A 'null' can be type-casted to any object reference type, but not to a primitive type So in C#, we need to be very careful about this fact

No comments:

Post a Comment