What is the longest legal statement block you can

2019-03-11 02:08发布

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 :-)

标签: c# keyword
6条回答
一夜七次
2楼-- · 2019-03-11 02:11
internal protected static volatile string foo = "bar";

That's 5.

查看更多
成全新的幸福
3楼-- · 2019-03-11 02:13

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 { }
                }
            }
        }
    }
}
查看更多
The star\"
4楼-- · 2019-03-11 02:14

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.

查看更多
ら.Afraid
5楼-- · 2019-03-11 02:25

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 // ...
查看更多
神经病院院长
6楼-- · 2019-03-11 02:25

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.

查看更多
地球回转人心会变
7楼-- · 2019-03-11 02:33

I guess it's infinite:

return null as string as string as string as string as string....
查看更多
登录 后发表回答