tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Examples for "(Not) interesting observation on LINQ”

3 May 2009 1 mins LINQ

After the post (Not) interesting observation on LINQ was out Michal Blaha asked me to show some example to show what I’m talking about. 😃

OK, here it is. This example shows the first observation from second paragraph (yep, it’s second 😉). I’m using only Where, for the sake of simplicity.

class Program
{
    static void Main(string[] args)
    {
        Class1 a = new Class1();
        var q = from x in a
                where x.Foo > 20
                select new { Bar = x.Foo };
    }
}
class Class1
{
    public int Foo { get; set; }
    public IEnumerable<Class1> Where(Func<Class1, bool> predicate)
    {
        return new[] { this };
    }
}

No IQueryable, no querying provider stuff, etc. Compiles without problems, and runs without complaining. No magic, right?

Now the third (last) paragraph.

class Program
{
    static void Main(string[] args)
    {
        Class1 a = new Class1();
        var q = from x in a
                where x.Foo > 20
                select new { Bar = x.Bar };
    }
}
class Class1
{
    public int Foo { get; set; }
    public IEnumerable<Class2> Where(Func<Class1, bool> predicate)
    {
        return new[] { new Class2() };
    }
}
class Class2
{
    public int Bar { get; set; }
}

The example is magically returning from Where IEnumerable of other class. 😃 Doing this with couple of standard LINQ operators may confuse your colleagues well. You can also check the “LINQ to Simpsons” from Bart de Smet to see comprehensive confusing.

Profile Picture Jiří Činčura is .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at www.tabsoverspaces.com.