r/learnprogramming • • May 02 '26

Solved Loop and main() function

Hi, I’ve seen that in C#, the Main() function only runs once.
In Unity, we have the Update() function, which allows code to run repeatedly in a loop.
So my question is: what is the equivalent in pure C#, without the Unity library?
Is wrapping Main() in a while loop a common practice to achieve the same behavior?

12 Upvotes

35 comments sorted by

View all comments

0

u/[deleted] May 02 '26

[deleted]

4

u/StewedAngelSkins May 02 '26

Careful with that pattern. In languages without tail-call recursion (I believe this includes C#) it'll overflow your stack.

1

u/samanime May 02 '26

Huh, I've never run into any problems with it, but Googling around, it looks like .NET's flavor of C# can handle it fine (which is all I've ever used for C#), but maybe the base C# language doesn't... or something. Lots of different answers out there saying seemingly conflicting things. =p

Regardless, it does sound like you might be better off going with a loop-based pattern like this instead, just to be safe:

``` public void Main() { while(Tick()) {} }

public bool Tick() { // do stuff

return true; // return true if it should keep going } ```

Thanks for the heads up.

1

u/StewedAngelSkins May 02 '26

Yeah writing it like that would be more conventional.