Search code examples
c#visual-studio

C# .NET 7.0: How to convert top-level-statement program file to classic style?


I've inherited a C# (.NET 7.0) project that includes program files written in the newer "top-level statement" style. I need to change these to the classic C# program file style. Is there a quick and easy way to do this?

The research I've done suggests that I can use ReSharper to do this. But our company does not have a ReSharper license. Thus, I need a way to accomplish this using only the built-in Visual Studio tools or by manually editing the project file.


Solution

  • Is there a quick and easy way to do this?

    Using the Visual Studio code fix, put the cursor in a line of code and pick "To explicit Program class":

    Convert top level statement to explicit Program class


    Otherwise:

    1. Open your Program.cs file in VS.
    2. Press Ctrl+A + Ctrl+X.
    3. Type out public static class Program{ public static async Task Main() {
    4. Press Ctrl+V.
    5. Type out } }.
    6. Press Ctrl+K + Ctrl+D to re-format the file (to correct indenting, etc).
    7. Save.

    • No changes to your .csproj file should be necessary.
    • Assuming you have the default settings still enabled, the act of pasting that C# code will automatically re-add the namespace-import using statements to the top of the file.
    • This answer also assumes you have file scoped namespaces enabled.