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



Question:

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


Solution: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 { }                  }              }          }      }  }  


Solution:2

I guess it's infinite:

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


Solution: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 // ...  


Solution:4

internal protected static volatile string foo = "bar";  

That's 5.


Solution: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.


Solution: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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »