Inside Man
Inside Man

Reputation: 4293

IList property automatic get set

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?

Upvotes: 3

Views: 1373

Answers (2)

NO TO OPENAI
NO TO OPENAI

Reputation: 685

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

Upvotes: 3

Xiaosu
Xiaosu

Reputation: 615

In C# 6 or higher, you can do:

public IList<Result> Results { get; set; } = new List<Result>();

Upvotes: 1

Related Questions