voxtm
voxtm

Reputation: 490

How to retrieve object from interface collection based on predicate specific to concrete class?

I have a collection of objects as a property in my class implementing IFoo. I'd like to add a method for retrieval of an item from the collection by type and predicate (specific to the concrete implementation). The problem I have is that I can't downcast from collection defined by interface to my concrete class (type cannot be inferred from usage) like so:

public HashSet<IFoo> Foos { get; } = new HashSet<IFoo>();

public T GetFoo<T>(Func<T, bool> predicate) where T : class
    {
        if (Foos != null && predicate != null)
        {
            var foos = Foos.Where(f => f is T);
            return foo = foos.FirstOrDefault(predicate);
        }

        return null;
    }

How can I do this?

Upvotes: 0

Views: 62

Answers (2)

John Koerner
John Koerner

Reputation: 38077

Since your HashSet is of type IFoo, it is expected that your predicate also uses IFoo. The easiest way to accomplish this is to change the signature of your method:

    public IFoo GetFoo<T>(Func<IFoo, bool> predicate) where T: IFoo, class

Upvotes: 2

voxtm
voxtm

Reputation: 490

Found a solution. I'm retrieving IFoo and downcasting in the predicate and other places I actually use it but not on retrieval:

 public IFoo GetFoo<T>(Func<IFoo, bool> predicate) where T : class
    {
        if (Foos != null && predicate != null)
        {
            var foos = Foos.Where(f => f is T);
            return foos.FirstOrDefault(predicate);
        }

        return null;
    }

Upvotes: 0

Related Questions