How compare classes with generic types in C#

799 views Asked by At

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();
}
1

There are 1 answers

5
Kenneth On BEST ANSWER

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>();