Shorthand way to return values that might be null


Problem: Suppose we have get-only property as below. In this we have a private variable and a public property both are list type.


        private List<User> _usr ;
        public List<User> lst
        {
            get
            {
                if (_usr == null)
                {
                    _usr = new List<User>();
                }

                return _usr;
            }
        }


How can I optimize this code or any shorthand way to write code of above scenario?

Answer: Yes we can, there are many way to write code in short to above code.


        private List<User> _usr ;
        public List<User> lst
        {
            get
            {
                _usr = _usr ?? new List<User>();
                return _usr;
            }
        }


Or


        private List<User> _usr ;
        public List<User> lst
        {
            get{return _usr ?? (new List<User>());}
        }


No comments:

Post a Comment

Please do not enter any spam link in the comment box.

Related Posts

How to drop a PostgreSQL database if there are active connections to it?

In PostgreSQL, you cannot drop a database if there are active connections to it. You must first terminate all connections to the database be...