I'd like a loop that uses a UInt16 (ushort) to loop through all of its values. However, this doesn't do it:
for( ushort i = 0; i < UInt16.MaxValue; i++ )
{
// do something
}
The problem is that the loop will quit when i == 0xFFFF and not "do something". If I change the 'for' statement to "for(ushort i = 0; i <= UInt16.MaxValue; i++ )", then it becomes an infinite loop because i never gets to 0x10000 because ushorts only go to 0xFFFF.
I could make 'i' an int and cast it or assign it to a ushort variable in the loop.
Any suggestions?
Use a do...while
loop
ushort i = 0;
do
{
// do something
} while(i++ < UInt16.MaxValue);
There is an interesting discussion of testing loops at the top vs. the bottom here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With