Jonathan Twite
Jonathan Twite

Reputation: 952

C# is there a difference between where() and where<T>()

In C# linq, is there a difference between A.where(...) and A.where<SomeClass>(...) where A is some type of suitable collection?

Upvotes: 1

Views: 136

Answers (1)

xanatos
xanatos

Reputation: 111870

In general no, because the compiler will infer the type T of the IEnumerable<> A and use as the generic parameter of the .Where<>()

but

You could force the Where<> to "use" a SomeClass that is a base class of the T type of the IEnumerable<> (this works because IEnumerable<> is covariant, so IEnumerable<subclass> can be "casted" to IEnumerable<baseclass>)...

The only practical result would be that you would "see" in the Where() a little "less" of T (and that if there are properties/methods of T that are "overwritten" by SomeClass you will access them without having to do casts)

Example:

public class MyClass
{
    public int GetNumber()
    {
        return 1;
    }
}

public class MySubClass : MyClass
{
    // Note the use of *new*. This isn't a virtual method!
    public new int GetNumber()
    {
        return 2;
    }
}

MySubClass[] coll = new[] { new MySubClass(), new MySubClass() };
var res = coll.Where(x => x.GetNumber() == 2).ToArray(); // 2 elements
var res2 = coll.Where<MyClass>(x => x.GetNumber() == 2).ToArray(); // 0 elements
var res3 = coll.Where<MyClass>(x => x.GetNumber() == 1).ToArray(); // 2 elements

Upvotes: 6

Related Questions