Quantcast
Channel: CodeFari
Viewing all articles
Browse latest Browse all 265

Shorthand way to return values that might be null

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


        privateList<User> _usr ;
        publicList<User> lst
        {
            get
            {
                if (_usr == null)
                {
                    _usr = newList<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.


        privateList<User> _usr ;
        publicList<User> lst
        {
            get
            {
                _usr = _usr ?? newList<User>();
                return _usr;
            }
        }


Or


        privateList<User> _usr ;
        publicList<User> lst
        {
            get{return _usr ?? (newList<User>());}
        }



Viewing all articles
Browse latest Browse all 265

Trending Articles