“Main” is a special method while defining assemblies. It’s an entry point of an executable application. Main runs in static context by is called by operating system to load the program into memory. Main does so by defining a startup object or logic.
static class Program { /// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { } }
style="display:block; text-align:center;"
data-ad-format="fluid"
data-ad-layout="in-article"
data-ad-client="ca-pub-5021110436373536"
data-ad-slot="9215486331">
Some important points regarding Main method are in earlier versions of C# are
Main can be called with/without parameters
You can either return integer value from Main or return void.
Consider below example where we will check license before starting a program and the API we call is having an async version.
/// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { if ( CheckLicense().Result) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } else { MessageBox.Show("Invalid License"); Application.Exit(); } } static async Task<bool> CheckLicense() { //Just random wait simultating a call to server which call server and check license await Task.Delay(4000); return true; }
style="display:block; text-align:center;"
data-ad-format="fluid"
data-ad-layout="in-article"
data-ad-client="ca-pub-5021110436373536"
data-ad-slot="9215486331">
As you can see in above code we need to call CheckLicense().Result method since we cannot use await inside Main method but this was before 7.1. C# 7.1 now supports async Main method so awaiting can be done for asynchronous methods inside Main as shown be modified version below
/// The main entry point for the application. /// </summary> [STAThread] async static Task Main() { if (await CheckLicense()) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } else { MessageBox.Show("Invalid License"); Application.Exit(); } } async static Task<bool> CheckLicense() { //Just random wait simultating a call to server which call server and check license await Task.Delay(4000); return true; }
style="display:block; text-align:center;"
data-ad-format="fluid"
data-ad-layout="in-article"
data-ad-client="ca-pub-5021110436373536"
data-ad-slot="9215486331">
So, the new feature additions are:
- Async Main method
- Appropriately the return type can now be Task and Task<int> as well apart from void and int
All code samples are available at my GitHub profile
I am a corporate trainer and solution architect and have a great team of software professionals. Please contact in case you need our services by sending email to contact@techprocompsoft.com. Here is our company website .