In my domain object I am mapping a 1:M relationship with an IList property.
For a good isolation, I make it read-only in this way:
private IList<PName> _property;
public ReadOnlyCollection<PName> Property
{
get
{
if (_property!= null)
{
return new ReadOnlyCollection<PName>(new List<PName>(this._property));
}
}
}
I don't like ReadOnlyCollection very much but found no interface solution for making the collection read-only.
Now I want to edit the property declaration to make it return empty list and not null
when it's empty, so I edited it in this way:
if (_property!= null)
{
return new ReadOnlyCollection<PName>(new List<PName>(this._property));
}
else
{
return new ReadOnlyCollection<PName>(new List<PName>());
}
but Property
is always null when I get it in my test.
As it's readonly and empty, it's safe to store this in a static:
private static readonly ReadOnlyCollection<PName> EmptyPNames = new List<PName>().AsReadOnly();
Then reuse it anywhere you need it, e.g.:
if (_property!= null)
{
return new ReadOnlyCollection<PName>(new List<PName>(this._property));
}
else
{
return EmptyPNames;
}
What if you set a default value to the IList
private IList<PName> _property = new IList<PName>();
public ReadOnlyCollection<PName> Property
{
get
{
return _property
}
}
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