What is the proper way to check for null values?

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

    If it will always be a string, you can cast:

    string y = (string)Session["key"] ?? "none";
    

    This has the advantage of complaining instead of hiding the mistake if someone stuffs an int or something in Session["key"]. ;)

提交回复
热议问题