2
votes

I wonder what is the difference between this code:

(Person)null

And this code

default(Person)

I think its the same. It acts the same to me. What are the nuances?

2

2 Answers

7
votes

default() returns the default value for the type. For reference types, that is null. For e.g. int that is the value 0, and for e.g. datetime, it is 0001-01-01 00:00. See the docs for other type defaults.

So default() behaves differently depending on the type.

The (Person)null cast of null, just gives you a person object that is null. I don't know when you would want to use that. In a variable declaration, it isn't necessary:

Person p = (Person)null;

is the same as

Person p = null;

It is in fact possible to use

var p = (Person)null;

and

var p = default(Person);
1
votes

Sometimes default keywords comes very handy when working with generic objects. It returns the default value when the object is not initialized. For example, we all know integers are initialized to 0 if not given any value. Characters are Empty when not given any value, objects are null when not assigned any value.

These values are assigned based on default keyword. Thus if we write :

int x = default(int);//will be assigned to 0

will be same as int x;

In case of Generic object when the type is undefined, we can use default to assign specific value to the object. Let us look at the sample :

public T GetDefault<T>()
{
return default(T);
} 

The function returns default value for each individual types sent. Thus

int defx = this.GetDefault<int>(); //will assign 0
char defy = this.GetDefault<char>(); // will assign null('\0')
object defz = this.GetDefault<object>(); // will assign null

Thus we can use default keyword to get the default assignments to the object very easily.

On the other hand The (Person)null cast of null, just gives you a person null object