What is the longest legal statement block you can

2019-03-11 01:30发布

问题:

I was writing some code in C#, and I found myself writing:

return new MyClass(...

when I noticed that both the return and the new were both C# keywords. So I wondered what is the longest legal sequence of keywords in C#. All I could think of is:

internal static override void MyFunc(...

Where internal static override void are all keywords. Can you think of a longer sequence of keywords?

Note: There's really no point to the question. I'm just hoping to pour more some fun on the fire :-)

回答1:

For 6:

new protected internal unsafe virtual decimal Foo() {...}

Edit for 7:

new protected internal unsafe virtual extern decimal Foo();

If we allow brackets and braces...

(edited the "lock", "new object()", "as" and "string" were contributed by others; see comments)

decimal Bar() {
    lock (new object() as string) {
        if (true) {
            checked {
                unsafe {
                    try {
                        do {
                            return default(decimal);
                            unchecked {break;}
                            continue;
                        } while (false);
                    }
                    catch { throw; }
                    finally { }
                }
            }
        }
    }
}


回答2:

I guess it's infinite:

return null as string as string as string as string as string....


回答3:

Here is another case that can be as long as you wish:

do do do do do do do do do do do do do do do // ...
while(x) while(x) while(x) while(x) while(x) // ...

With contextual keywords you can also have

await await await await await await await // ...


回答4:

internal protected static volatile string foo = "bar";

That's 5.



回答5:

One more variant with method definition (found by my colleague):

protected internal override sealed unsafe async void await() { ... }

Makes 8 keywords in a row. Uses the fact that await is a contextual keyword, so it can be reused for method name.



回答6:

Can I cheat?

internal protected static volatile StringBuilder @string = 
  new StringBuilder(int.Parse("12"));

Using the fact that I can use a keyword or other reserved term as a variable name if I prepend it with an @ - comes in at 9 if you allow the duplication of StringBuilder.



标签: c# keyword