views:

99

answers:

4

I have a dictionary whose values I'd like to return to a caller like this:

public ICollection<Event> GetSubscriptions()
{
    return isLockDown ? Enumerable.Empty<Event> : subscriptionForwards.Values;
}

Unfortunately, the empty enumerable type is not compatible with the stated return type. Is there another BCL facility for this?

p.s. no, it does not work to cast both targets of the ternary as (ICollection<Event>)

+2  A: 

Since arrays implement IList<T> which in turn extends ICollection<T>, you could use an empty array for your empty collection.

public ICollection<Event> GetSubscriptions()
{
    return isLockDown ? new Event[0] : subscriptionForwards.Values;
}

Edit:
As others have pointed out, you could also return new List<Event>(). The difference will be:

  • new Event[0] is readonly, callers cannot add elements to it (an exception will be thrown if they try)
  • new List<Event>() is mutable, callers can add elements to it (although each caller gets its own list, so changes aren't visible to other callers)
Greg
That is what I have done (though I made a static readonly `empty = new Event[0]`). I'll wait till next week to collect more answers, but without them I'll mark yours.
Brent Arias
`new List<Event>()` could also work.
Gabe
Object instantiation is not really that expensive. Unless this method is being called hundreds of times per second, creating a static variable for the sake of holding an empty collection is, in my opinion, a premature optimization.
Daniel T.
+1  A: 

If you really to still use Enumerable.Empty you could do this:

public ICollection<Event> GetSubscriptions()
{
    return isLockDown ? Enumerable.Empty<Event>.ToList() : subscriptionForwards.Values;
}
Matthew Manela
+1  A: 

You could use this:

public ICollection<Event> GetSubscriptions()
{
    return isLockDown ? new Collection<Event>() : subscriptionForwards.Values;
}

You need to add this reference in order for it to work:

using System.Collections.ObjectModel;
Ivan Ferić
+1  A: 

You could always create your own empty collection. At least the construction only happens once.

private static readonly ICollection<Event> EMPTY_EVENTS = new List<Event>();

public ICollection<Event> GetSubscriptions()
{
    return isLockDown ? EMPTY_EVENTS : subscriptionForwards.Values;
}
Rodney Foley