1

Why is LINQ allowed to have spaces in the statement? An example statement:

var questions = from item in db.questions
                select item;

As a programmer, we cannot create functions or methods with spaces in them, or anything that resembles the LINQ syntax. Is this something that is just specially parsed by the language? Would there be any way to let programmers make up their own LINQ-like statements?

BobTurbo
  • 141
  • 1
  • 1
  • 9
  • Related: http://stackoverflow.com/questions/7247306/is-it-possible-to-create-c-sharp-language-modifications-as-did-linq –  Oct 25 '11 at 08:21

2 Answers2

4

Because they are "keywords" (technically they are "contextual keywords". They are "keywords" only in certain places) :-) Look here: Query Keywords (C# Reference) and C# Keywords

Why can you write public static void with spaces? Because they are keywords :-)

And no, you can't add new keywords to C#.

(but note that you can use the LINQ syntax on non-IEnumerable/IQueryable objects. LINQ syntax is converted "blindly" to specific method names. The compiler doesn't check if they are really IEnumerable<T> or IQueryable<T>)

Try this:

class Test
{
    public Test Where(Func<Test, bool> predicate)
    {
        Console.WriteLine("Doing the Where");
        return this;
    }

    public T Select<T>(Func<Test, T> action)
    {
        Console.WriteLine("Doing the Select");
        return action(this);
    }
}

var res = from p in new Test() where p != null select new Test();
xanatos
  • 109,618
  • 12
  • 197
  • 280
1

It's syntactic sugar that the compiler understands. You can't change the compiler so can't do the same I'm afraid

Firedragon
  • 3,685
  • 3
  • 35
  • 75