Atrotygma
Atrotygma

Reputation: 1153

Implicitly convert collection (HashSet) to IEnumerable<T>

I have a simple abstract enumeration class:

public abstract class Enumeration<T> {

    protected readonly T _value;
    private static readonly HashSet<Enumeration<T>> _values
        = new HastSet<Enumeration<T>>();

    protected Enumeration(T value) {
        _value = value;
        _values.Add(this);
    }

}

Now I would like to have a method that returns every element in the HashSet, but not the HashSet itself ( -> as an IEnumerable).

But this doesn't work:

public static IEnumerable<T> GetValues() {
     return _values;
}

because I cannot implicitly convert HashSet to IEnumerable<T>, of course. The only way I can think of is looping through the HashSet and yielding every element, but I wonder if there's a way to do this automatically, like when you implicitly cast a list to an IEnumerable<T>.

Upvotes: 3

Views: 11567

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460340

public static IEnumerable<T> GetValues()
{
    return _values.Select(e => e._value);
}

Upvotes: 0

SLaks
SLaks

Reputation: 888223

You can implicitly convert HashSet<T> to IEnumerable<T>, because HashSet, like ewvery other generic collection type, implements IEnumerable<T>.

However, for obvious reasons, you cannot convert HashSet<U> to IEnumerable<T>, unless U is convertible to T (in which case you can use an implicit covariant conversion).

Your HashSet is (but probably should not be) a collection of Enumeration<T>, not T.

Upvotes: 10

Related Questions