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?
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;
}
}
In C# 6 or higher, you can do:
public IList<Result> Results { get; set; } = new List<Result>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With