tugberk
tugberk

Reputation: 58494

infinite loop example with minimum code in c#

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

Answers (8)

mdec
mdec

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

Vilx-
Vilx-

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

Christoffer
Christoffer

Reputation: 12918

If you need a bit more obscurity, this might be what you are after:

for (;;) { }

Or even

l: goto l;

Upvotes: 6

Vilx-
Vilx-

Reputation: 107052

In the spirit of Code Golf:

for(;;);

Upvotes: 3

FIre Panda
FIre Panda

Reputation: 6637

Try this, an example of infinite loop.

while(true)
{

}

Upvotes: 0

Martin Liversage
Martin Liversage

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

V4Vendetta
V4Vendetta

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

abatishchev
abatishchev

Reputation: 100366

Infinite loop:

while (true)
{
    // do stuff
}

to break it:

while (true)
{
    if (condition)
        break;
}

Upvotes: 9

Related Questions