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

What is the Use of isNaN Function in JavaScript? A Comprehensive Explanation for Effective Input Validation

In the world of JavaScript, input validation is a critical aspect of ensuring that user-provided data is processed correctly. One indispensa...