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

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

    When constraints have not been applied to restrict a generic type parameter to be a reference type, then a value type, such as a struct, could also be passed. In such cases, comparing the type parameter to null would always be false, because a struct can be empty, but never null

    wrong code

    public void TestChanges(T inputValue)
    
                try
                {
                    if (inputValue==null)
                        return;
                    //operation on inputValue
    
               }
                catch
                {
                    // ignore this.
                }
            }
    

    corrected

    public void TestChanges(T inputValue)
    
                try
                {
                    if (object.Equals(inputValue, default(T)) )
                        return;
                    //operation on inputValue
    
               }
                catch
                {
                    // ignore this.
                }
            }
    

提交回复
热议问题