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
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:
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
yep, there are no free functions in C#
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!
The CLR probably doesn't support it, but since C++/CLI is fancy C++, it supports them in some way
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 cakeI think F# does?