Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an empty ReadOnlyCollection

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.

like image 265
gt.guybrush Avatar asked Sep 17 '13 14:09

gt.guybrush


2 Answers

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;
}
like image 63
weston Avatar answered Nov 20 '22 22:11

weston


What if you set a default value to the IList

private IList<PName> _property = new IList<PName>();
public ReadOnlyCollection<PName> Property
{
    get
    {
        return _property
    }
}
like image 1
NicoTek Avatar answered Nov 20 '22 21:11

NicoTek