Googling is only coming up with the keyword, but I stumbled across some code that says
MyVariable = default(MyObject);
and I am wondering
Specifies the default value of the type parameter.This will be null for reference types and zero for value types.
See default
The default
keyword returns the "default" or "empty" value for a variable of the requested type.
For all reference types (defined with class
, delegate
, etc), this is null
. For value types (defined with struct
, enum
, etc) it's an all-zeroes value (for example, int 0
, DateTime 0001-01-01 00:00:00
, etc).
It's mostly used with generic code that can be applied to both reference and value types, because you can't assign null
to a value type variable.
Another good use of default(T)
is when compiler can't determine returning type, like in here
class X
{
public int? P {get; set;}
}
// assigning in code
var x = new X();
// consider coll["key"] returns object boxed value
// data readers is one such case
x.P = myReader["someColumn"] == DbNull.Value ? default(int?) : (int)myReader["someColumn"];