- 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 first 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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…