What is the proper way to check for null values?

前端 未结 10 1986
刺人心
刺人心 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:51

    This is my little type safe "Elvis operator" for versions of .NET that do not support ?.

    public class IsNull
    {
        public static O Substitute(I obj, Func fn, O nullValue=default(O))
        {
            if (obj == null)
                return nullValue;
            else
                return fn(obj);
        }
    }
    

    First argument is the tested object. Second is the function. And third is the null value. So for your case:

    IsNull.Substitute(Session["key"],s=>s.ToString(),"none");
    

    It is very useful for nullable types too. For example:

    decimal? v;
    ...
    IsNull.Substitute(v,v.Value,0);
    ....
    

提交回复
热议问题