What is the purpose of main() function in C#?

Main function is the entry point for your program. When you execute a program, the operating system will check for the Main function and execute the code statements in it. Consider the following example:



namespace Application1 {
public class sampleClass {
public static void sampleMethod() {
Console.WriteLine("Executing sampleMethod..");
}
}
}

When you execute the above program, you will end up in the following error:
Program ‘Application1.exe' does not contain a static 'Main' method suitable for an entry point

This is because the above program does not include Main function. To make it work, include the following Main function inside sampleClass:

public static void Main() {
sampleMethod();
}

Now when you execute the program, you will get the following output:
Executing sampleMethod..

The Main function can take four different forms. They are mentioned below:

static void Main() { }
static void Main(string[ ]args) { }
static int Main() { }
static int Main(string[ ] args) { }

But remember that your program can have only one Main function which can have any of the above shown signatures. If multiple Main functions are defined, then you will get this error:
Program ‘Application1.exe' has more than one entry point defined: 'Application1.sampleClass.Main()'

| What is Private Access Modifier in C#? | What is Protected Access Modifier in C#? | What is Protected Internal Access Modifier in C#? | What is Public Access Modifier in C#? | What is the difference between virtual and abstract keywords in .NET? | What is the importance of Microsoft Application Blocks in .NET Architecture? | What is the need for Factory Method in C# | What is the purpose of ArrayList in .NET? | What is the purpose of Datareader in ADO.NET? | What is the purpose of Dataset in ADO.NET? | What is the purpose of finally block in C#? | What is the purpose of interlocked class in .NET? | What is the purpose of main() function in C# | What is the purpose of ManualResetEvent in .NET? | What is the purpose of sealed method in C#? | What is the purpose of Thread.Join() method in .NET? | What is the purpose of Thread.Sleep() method in .NET? | What is the purpose of throw keyword in C#? | What is the usage of ENUM in .NET? |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.