C
C#6d ago
tommy

Why do we enclose the `Main` function inside of a class in C#?

After learning C++, I think it makes sense to include the main function outside of a class. Why do we not do it in C#? Like what disadvantage I would have by not including the main function in a class in C++? Would it be accessible to everyone? Does including the Main method in a class in C# make it "safer" than it being present at a global scope? What is the reason behind this?
8 Replies
Marvin
Marvin6d ago
there is just not the concept of declaring methods somewhere loose outside a class / in a namespace. Nowadays you can just write your code without any method or class in the Program.cs file like the following:
No description
Pobiega
Pobiega6d ago
C# fundamentally doesn't allow methods outside of classes, so that's why. Even in Marvin's example, a class and main method are generated by the compiler
Jimmacle
Jimmacle6d ago
yep, there are no free functions in C#
LPeter1997
LPeter19976d ago
Fun fact: .NET has the concept of free functions, but since C# is the main "dictator" and user of the platform, almost nothing ended up using it as most things want to be "C#-compatible". C++.NET uses them tho!
Rosentti
Rosentti6d ago
The CLR probably doesn't support it, but since C++/CLI is fancy C++, it supports them in some way
LPeter1997
LPeter19976d ago
Technically it's the unspeakable <Module> class yes. Which makes me wonder why no languages want to support it, if a compiler implements a metadata reader for classes anyway, reading up the members of <Module> should be a piece of cake
jcotton42
jcotton426d ago
I think F# does?
Petris
Petris4d ago
No description
Want results from more Discord servers?
Add your server