C# Byte Iteration Question
This one is a great c# interview question – short and simple, but tricky.
static void Main(string[] args)
{
for (byte b = byte.MinValue; b <= byte.MaxValue; b++)
Console.Write(b);
}
// A little tip
// byte.MinValue = 0
// byte.MaxValue = 255
How many times the above statement will be executed ?
C# Byte Iteration Question,
Categories: C#, Interview Questions, Programming, Teasers, Tips & Tricks


256?
Nope. As i said, it’s simple… but tricky.
endless loop?
Correct
And now the second part.
What do you have to change to throw an overflow exception in the above code ?
Forever…until you stop it or get out of memory exception
Put the for loop in a checked block.
True
checked { for (byte b = byte.MinValue; b < = byte.MaxValue; b++) Console.Write(b); }@Kossovsky Alexander
Add “checked {}” expression? BTW thank you for reminding about this feature. It surely indicates that I have to refresh my knowledge on C# pecularities.
That is what my blog is about. Reminding all of you (and my self) all the the stuff we shouldn’t forget
@Mio
Actually, you get an ‘out of memory’ exception not because of the ‘for’ structure itself, but because of Console.Write(b).
@mmp
Why does it produce the exception in the first place?
Why it is endless loop. Any explaination will help.
Byte.MaxValue +1 = Byte.MinValue so the for never ends. For this not to happen you have to use checked{}.