What does default(object); do in C#?

  • For a reference-type, it returns null
  • For a value-type other than Nullable<T> it returns a zero-initialized value
  • For Nullable<T> it returns the empty (pseudo-null) value (actually, this is a re-statement of the second bullet, but it is worth making it explicit)

The biggest use of default(T) is in generics, and things like the Try... pattern:

bool TryGetValue(out T value) {
    if(NoDataIsAvailable) {
        value = default(T); // because I have to set it to *something*
        return false;
    }
    value = GetData();
    return true;
}

As it happens, I also use it in some code-generation, where it is a pain to initialize fields / variables – but if you know the type:

bool someField = default(bool);
int someOtherField = default(int)
global::My.Namespace.SomeType another = default(global::My.Namespace.SomeType);

Leave a Comment