What is the proper way to check for null values?

前端 未结 10 2025
刺人心
刺人心 2020-12-04 08:05

I love the null-coalescing operator because it makes it easy to assign a default value for nullable types.

 int y = x ?? -1;

That\'s great,

10条回答
  •  情书的邮戳
    2020-12-04 08:53

    Skeet's answer is the best - in particularly I think his ToStringOrNull() is quite elegant and suits your need best. I wanted to add one more option to the list of extension methods:

    Return original object or default string value for null:

    // Method:
    public static object OrNullAsString(this object input, string defaultValue)
    {
        if (defaultValue == null)
            throw new ArgumentNullException("defaultValue");
        return input == null ? defaultValue : input;
    }
    
    // Example:
    var y = Session["key"].OrNullAsString("defaultValue");
    

    Use var for the returned value as it will come back as the original input's type, only as the default string when null

提交回复
热议问题