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

后端 未结 9 2342
误落风尘
误落风尘 2020-11-28 03:03

Googling is only coming up with the keyword, but I stumbled across some code that says

MyVariable = default(MyObject);

and I am wondering

9条回答
  •  不知归路
    2020-11-28 03:38

    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.

提交回复
热议问题