How to Return an Empty ValueCollection
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;
}
Unfort开发者_运维百科unately, 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>)
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)
If you really to still use Enumerable.Empty you could do this:
public ICollection<Event> GetSubscriptions()
{
return isLockDown ? Enumerable.Empty<Event>.ToList() : subscriptionForwards.Values;
}
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;
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;
}
精彩评论