'How to add static methods inside "Program" in Visual Studio 2022 [duplicate]

I'm using Visual Studio 2022 with .NET 6.0 framework. The following no longer exists and I usually write whatever that'll be inside this static void Main method directly in the "Program" that is automatically generated when creating a new project.

static void Main(string[] args)

However, if I need to have some static methods outside the static void Main method, it won't work to just write them inside "Program". How can I add these static methods then?

Thank you so much for your help!!



Solution 1:[1]

You are probably referring to "top level statements". This is when you dispense with the whole main method, since it is just boilerplate, and just write code directly in a code file.

If you need any helper methods you should just add a new code file and add the methods in a static class:

public static class MyHelpers{
    public static int MyAddMethod(int a, int b) => a + b;
}

And just call it like MyHelpers.MyAddMethod(1, 2).

As gunr2171 points out, you can also put classes at the end of your top-level file. But for your own and others sanity I would highly recommend trying to stick with one class per file.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1