Default value for user defined class in C#

Benny picture Benny · Dec 17, 2009 · Viewed 71.1k times · Source

I see some code will return the default value, so I am wondering for a user defined class, how will the compiler define its default value?

Answer

David Hedlund picture David Hedlund · Dec 17, 2009

To chime in with the rest, it will be null, but I should also add that you can get the default value of any type, using default

default(MyClass) // null
default(int) // 0

It can be especially useful when working with generics; you might want to return default(T), if your return type is T and you don't want to assume that it's nullable.