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

后端 未结 9 2302
误落风尘
误落风尘 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

    Specifies the default value of the type parameter.This will be null for reference types and zero for value types.

    See default

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-28 03:42

    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"];
    
    
    
    0 讨论(0)
提交回复
热议问题