c# method in generic class only for certain types

Viewed 8423

I'm trying to define a method on a generic class that is limited to a specific type. I have come up with this:

interface IHasId 
{
    int Id { get; }
}

public class Foo<T>
{
    private List<T> children;

    public IHasId GetById(int id)
    {
        foreach (var child in children.Cast<IHasId>())
        {
            if (child.Id == id)
            {
                return child;
            }
        }

        return null;
    }
}

It will work, but it looks like a code smell...it seems like there should be a way to get the compiler to enforce this. Something like:

public class Foo<T>
{
    public IHasId GetById<TWithId>(int id) where TWithId : IHasId {}
}

or, even better:

public class Foo<T>
{
    public IHasId GetById(int id) where T : IHasId {}
}

I saw a few posts on this related to Java, and one talking specifically about constraining T to an enum, but nothing directly on point.

5 Answers
Related