What is the proper way to check for null values?

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

    My preference, for a one off, would be to use a safe cast to string in case the object stored with the key isn't one. Using ToString() may not have the results you want.

    var y = Session["key"] as string ?? "none";
    

    As @Jon Skeet says, if you find yourself doing this a lot an extension method or, better, yet maybe an extension method in conjunction with a strongly typed SessionWrapper class. Even without the extension method, the strongly typed wrapper might be a good idea.

    public class SessionWrapper
    {
        private HttpSessionBase Session { get; set; }
    
        public SessionWrapper( HttpSessionBase session )
        {
            Session = session;
        }
    
        public SessionWrapper() : this( HttpContext.Current.Session ) { }
    
        public string Key
        {
             get { return Session["key"] as string ?? "none";
        }
    
        public int MaxAllowed
        {
             get { return Session["maxAllowed"] as int? ?? 10 }
        }
    }
    

    Used as

     var session = new SessionWrapper(Session);
    
     string key = session.Key;
     int maxAllowed = session.maxAllowed;
    

提交回复
热议问题