Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add methods to Program.cs in .NET 6

Tags:

c#

.net-6.0

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?

like image 202
AliveInTheCircuits Avatar asked Sep 10 '25 22:09

AliveInTheCircuits


1 Answers

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://learn.microsoft.com/en-gb/dotnet/core/tutorials/top-level-templates

like image 79
jason.kaisersmith Avatar answered Sep 13 '25 13:09

jason.kaisersmith