Search code examples
c#genericsgeneric-type-argument

How compare classes with generic types in C#


How can I write the below code with is T

public IList<IElement> OfClass(Type type)
{
    return list
        .Where(o => o.GetType() == type)
        .ToList();
}

Something like this:

public IList<IEtabsElement> OfClass(....)
{
    return list
        .Where(o => o is ...)
        .ToList();
}

UPDATE This is my solution, so far. Is it okay?

public IList<IElement> OfClass<T>()
{
    return list
        .Where(o => o is T)
        .ToList();
}

Solution

  • You can create a generic method instead:

    public IList<T> OfClass<T>()
    {
        return list
            .Where(o => o.GetType() == typeof(T))
            .ToList();
    }
    

    This would work, but is the same as the existing method OfType, for example:

    var myvehicles = new List<Vehicle> { new Car(), new Bike()};
    var mycars = myvehicles.OfType<Car>();