What is the longest legal statement block you can make with only C# keywords?

独自空忆成欢 提交于 2019-12-03 06:53:47

问题


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.



来源:https://stackoverflow.com/questions/672977/what-is-the-longest-legal-statement-block-you-can-make-with-only-c-sharp-keyword

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!