In the Program.cs for .NET 5, you could add methods under the Main(string[] args) method. With .NET 6, the Main method exists, but isn't physically included in the Program.cs file by default. To that end, I'm wondering how you add methods to Program.cs. For example:
// .NET 5
public class Program
{
static void Main(string[] args)
{
// body
}
public static void MyMethodHere()
{
// method body
}
}
How would you add the MyMethodHere() class in .NET 6 in Program.cs without manually typing out the whole Program class and Main method?
CodePudding user response:
You just type out the method that you require and then call it!.
Console.WriteLine("Hello, World from Main!");
MyMethodHere();
static void MyMethodHere()
{
Console.WriteLine("MyMethodHere says hello World!");
}
But you can still type it out in full the same as you done before.
What I have done several times for simple console programs is to create the project with .net 5, this then generates using the "old" template, and then I just update TargetFramework
it to .net 6 before I do any coding.
See also the guide from MS: https://docs.microsoft.com/en-gb/dotnet/core/tutorials/top-level-templates
CodePudding user response:
.NET 6 has this new feature that allows minimal main. They unfortunately use it by default in new console projects. Its very confusing. Anyway you can write the old main just like you used to. You just have to type out all the code, or cut and paste from an old project
CodePudding user response:
This would work as well:
SayHello();
void SayHello()
{
Console.WriteLine("Hello World");
}
Methods are possible, but without the access modifiers. The compiler internally creates a static class.