Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IList property automatic get set

Tags:

c#

Currently, If I want to declare a property for my class, I write this line of code:

public string Target { get; set; }

Now for IList (generics), I do something like this:

IList<Result> _Results;
public IList<Result> Results
{
    get
    {
        if (_Results == null)
            _Results = new List<Result>();
        return _Results;
    }
    set
    {
        _Results = value;
    }
}

in get section I check if the list is null, then I will create a new one... How can I avoid this part and have a less and more clear code?

like image 767
Inside Man Avatar asked Mar 06 '26 13:03

Inside Man


2 Answers

If using C# 6 you can use null-coalesce operator ??:

IList<Result> _Results;
public IList<Result> Results
{
    get => _Results ?? (_Results = new List<Result>());

    set
    {
        _Results = value;
    }
} 
like image 187
Minijack Avatar answered Mar 08 '26 01:03

Minijack


In C# 6 or higher, you can do:

public IList<Result> Results { get; set; } = new List<Result>();
like image 38
Xiaosu Avatar answered Mar 08 '26 01:03

Xiaosu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!