A Crazy C# Question

by Dmitri June 16, 2009 00:50

Today I really fell over while trying to answer a question about a (fairly stupid) C# expression. It went something like the following:

Consider the following code:

int i = 0;
while (i < 10)
{
  Console.WriteLine(i++);
}
while (i >= 10);

This code:

  1. Will not compile
  2. Will print numbers from 0..9
  3. Will print numbers from 0..9 and then 9 forever
  4. Will print numbers from 0 to ∞

Something like this. At first I thought this wouldn’t compile, but in fact my SnippetCompiler ate it just fine. I thought I was going insane. Then I assumed that this construct is, in fact, allowed (maybe a bug in the C# language spec?) and it acts as a double-ended do, cycling the precondition while before cycling the postcondition while, thus yielding the answer 4.

And then it finally hit me: a while loop doesn’t need a comma after it. What this meant is that you could write the code as follows:

int i = 0;
while (i < 10)
{
  Console.WriteLine(i++);
}
// empty while loop!
while (i >= 10);

It was a trick question, of course, but it goes to show that vigilance against blatant trickery is often more useful than scientific analysis. Another lesson learned.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

c#

Comments

Comments are closed

Powered by BlogEngine.NET 1.4.5.0

About the author

St. Petersburg ALT.NET Group

My name is Dmitri Nesteruk, I'm a .Net developer, process/project manager and user group leader.

I co-ordinate the activity of several professional organizations, including the St. Petersburg .Net User Group, the St. Petersburg Alt.Net User Group, and others. If you are a techie and want to give a talk on a .Net-related topic, I am your point of contact. Don't be shy!