What is the proper way to check for null values?

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

    You could also use as, which yields null if the conversion fails:

    Session["key"] as string ?? "none"
    

    This would return "none" even if someone stuffed an int in Session["key"].

提交回复
热议问题