Along with the many changes .NET Core has brought to Modern Development, one that seems particularly confusing to new students is the idea of top-level statements (I’m going to use TLS for brevity here, not to be confused with Transport Layer Security. Yes, I’m freelancing).
(And yes, I still want to use the “Core” reference since there’s so many apps still out there using .NET Framework. Hey, at least they skipped the 4.x version for Core, and we’re on an annual release schedule for new versions now. Hallelujah.)
The reason for the confusion is change, of course, because for years, we had your standard Main method, like so:
There’s really not that much to Top-level statements other than hiding some of the plumbing. There’s an “implicit Main” method (It’s not actually called Main internally, but it doesn’t really matter because you’re never referring to it in code).
There’s a few other things to be watchful about, too:
— When you use TLS, you’re also signing up for implicit usings, to bring your referenced namespaces into scope. For console apps, that’s currently 7 common namespaces. Other app templates will generate other usings based on app type.
— If you want to opt out, edit your project file to disable implicit usings and go on as before, manually adding where needed.
— You can also add your own using statements directly into the Program.cs file (Or whatever you name it), but they have to be at the top before any executable statements, or your project won’t build.
— Namespaces and types are also allowed but they have to appear after your top-level statements.
— Using TLS also restricts your ability to have multiple Main methods and designate one of them as the startup when you run the command line. The file with the TLS in it has to be the only “Main” method
If this is all too much to track, Visual Studio still gives you an option to go the “old way” (Sorry, “Classic”!) when you first create the project.
(If you’re using the command line to create the project as we often do in Visual Studio Code, there’s a recently-added option that allows you to generate an actual Main, just add –use-program-main when you execute dotnet new console).
That’s really all there is to it. Here’s to change. Happy coding!
No Comments Yet