C
C#13mo ago
Karto

❔ How does the main method work?

I've only ever used c# in unity, so i've never worked outside the context of making games, so using the main method is very new to me. Since the main method needs to be static anything i use in it requires being static. How do you navigate around this?
6 Replies
Doombox
Doombox13mo ago
class Program
{
static void Main() => new Program().Run();
private void Run()
{
// code here...
}
}
class Program
{
static void Main() => new Program().Run();
private void Run()
{
// code here...
}
}
is generally the simplest way to get out of the static context your code starts in it's certainly what I do, with the new top level statement you can also do
// Startup.cs
new Program().Run():
// Startup.cs
new Program().Run():
then
// Program.cs
class Program
{
public void Run() { /* ... */ }
}
// Program.cs
class Program
{
public void Run() { /* ... */ }
}
WhiteBlackGoose
WhiteBlackGoose13mo ago
Since the main method needs to be static anything i use in it requires being static.
you can still create instances of types and call their non-static methods
Karto
Karto13mo ago
Awesome, thanks guys
cap5lut
cap5lut13mo ago
in addition to what the generic host does, there is also ConsoleAppFramework which adds some argument parsing the execute commands (similar to controllers in asp.net mvc) https://github.com/Cysharp/ConsoleAppFramework
GitHub
GitHub - Cysharp/ConsoleAppFramework: Micro-framework for console a...
Micro-framework for console applications to building CLI tools/Daemon/Batch for .NET, C#. - GitHub - Cysharp/ConsoleAppFramework: Micro-framework for console applications to building CLI tools/Daem...
JakenVeina
JakenVeina13mo ago
large scale apps generally end up looking something like this...
public static void Main()
{
using var myApp = new Application()
{
// settings and configuration
};

myApp.Run();
}
public static void Main()
{
using var myApp = new Application()
{
// settings and configuration
};

myApp.Run();
}
Accord
Accord13mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity. Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts