Reputation: 58494
Can you give me an infinite loop example on c# with minimum code? I came up with something but I thought there could be more easier way.
Upvotes: 4
Views: 11635
Reputation: 5252
The typical examples are the for and while loops. For example
for(;;)
{}
and
while(true)
{}
However, basically any looping construct without a break or a terminating condition will loop infinitely. Different developers have different opinions on which style is best. Additionally, context may sway which method you choose.
Upvotes: 23
Reputation: 107052
Though not exactly an infinite loop, this will have the same practical effect and consume WAY less CPU. :)
System.Threading.Thread.Sleep(-1);
Upvotes: 3
Reputation: 12918
If you need a bit more obscurity, this might be what you are after:
for (;;) { }
Or even
l: goto l;
Upvotes: 6
Reputation: 106946
while (true);
That should be enough.
The generated IL is:
IL_0000: br.s IL_0000
The code unconditionally transfers control to itself. A great way to waste CPU cycles.
Upvotes: 11
Reputation: 38230
Call a method within the same method and you have an infinite loop happening (Only conditions force you to break the loop)
void HelloWorld()
{
HelloWorld();
}
Upvotes: -3
Reputation: 100366
Infinite loop:
while (true)
{
// do stuff
}
to break it:
while (true)
{
if (condition)
break;
}
Upvotes: 9