WiseTechGlobal / WTG.Analyzers

Analyzers from WiseTech Global to enforce our styles, behaviours, and prevent common mistakes.
Other
16 stars 3 forks source link

Warn against patterns that cause unexpected conversion from `IQueryable<>` to `IEnumerable<>`. #160

Closed brian-reichle closed 2 years ago

brian-reichle commented 2 years ago

Add an analyzer to warn against using one of the following "Enumerable" extension methods on an IQueryable<>.

If you pass in a delegate filter, it will pick the overload from Enumerable instead of the one from Queryable.

IFoo GetFoo(IQueryable<IFoo> source)
    => source.Where(Filter).FirstOrDefault(); // Uses Enumerable.Where
static bool Filter(IFoo foo) => foo.Class == "Magic";

IFoo GetFoo(IQueryable<IFoo> source)
    => source.Where(foo => foo.FO_Class == "Magic").FirstOrDefault(); // Uses Queryable.Where

This means that the IQueryable<> will be treated as an IEnumerable<> and the filter will be applied locally. This is usually not what is expected and so the warning would help nudge the developer. If the developer really did want this, they can use .AsEnumerable().

IFoo GetFoo(IQueryable<IFoo> source)
    => source.AsEnumerable().Where(Filter).FirstOrDefault();
static bool Filter(IFoo foo) => foo.Class == "Magic";