How to return an empty ReadOnlyCollection

In my domain object, I map 1: M relationships to the IList property.

For good isolation, I do it read-only as follows:

private IList<PName> _property;
public ReadOnlyCollection<PName> Property
{
    get
    {
        if (_property!= null)
        {
            return new ReadOnlyCollection<PName>(new List<PName>(this._property));
        }
    }
}

I do not really like ReadOnlyCollection, but did not find an interface for creating a read-only collection.

Now I want to edit the property declaration so that it returns an empty list, and not nullwhen it is empty, so I edited it as follows:

if (_property!= null)
{
    return new ReadOnlyCollection<PName>(new List<PName>(this._property));
}
else
{
    return new ReadOnlyCollection<PName>(new List<PName>());
}

but Propertyalways null when I get it in my test.

+4
source share
4 answers

What to do if you set the default value for IList

private IList<PName> _property = new IList<PName>();
public ReadOnlyCollection<PName> Property
{
    get
    {
        return _property
    }
}
+1

, :

private static readonly ReadOnlyCollection<PName> EmptyPNames = new List<PName>().AsReadOnly();

, :

if (_property!= null)
{
    return new ReadOnlyCollection<PName>(new List<PName>(this._property));
}    
else
{
    return EmptyPNames;
}
+3

, IEnumerable ReadOnlyCollection:

private IList<PName> _property = new List<PName>();
public IEnumerable<PName> Property
{
    get
    {
        return _property;
    }
}
+1

Another possible solution is to edit the class constructor as follows:

public MyObject (IList<PName> property)
{
  this._property = property ?? new List<PName>();
}
0
source

Source: https://habr.com/ru/post/1502625/


All Articles