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

后端 未结 9 2333
误落风尘
误落风尘 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: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"];
    
    
    

提交回复
热议问题