Aug 5, 2016

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>());}
        }