In C#, you can define methods within a class, including the Main
method that serves as the entry point for your program. Here’s an example of how to define methods within the Program
class:
using System;
class Program
{
static void Main()
{
// Call the SayHello method
SayHello();
// Call the AddNumbers method
int sum = AddNumbers(5, 10);
Console.WriteLine("The sum of 5 and 10 is {0}", sum);
}
// A method that says hello
static void SayHello()
{
Console.WriteLine("Hello!");
}
// A method that adds two numbers
static int AddNumbers(int num1, int num2)
{
int result = num1 + num2;
return result;
}
}
In this program, the Main
method calls two other methods: SayHello
and AddNumbers
. The SayHello
method simply writes the text “Hello!” to the console. The AddNumbers
method takes two integer parameters, adds them together, and returns the result.
To define a method within a class, you need to specify the method’s access level (such as public
or private
), the return type of the method (if any), the method name, and the parameters (if any). Here’s the general syntax for defining a method:
[access level] [return type] [method name]([parameters])
{
// Method body
}
For example, the SayHello
method in the previous program is defined like this:
static void SayHello()
{
Console.WriteLine("Hello!");
}
This method has an access level of static
, which means it can be called without creating an instance of the Program
class. It has a return type of void
, which means it doesn’t return any value. And it has no parameters.
Similarly, the AddNumbers
method is defined like this:
static int AddNumbers(int num1, int num2)
{
int result = num1 + num2;
return result;
}
This method has an access level of static
, a return type of int
, and two integer parameters named num1
and num2
.
By defining methods within your class, you can break your program’s functionality into smaller, more manageable pieces that can be tested and reused in other parts of your code.
Our team here at LearningDot.NET hope you enjoyed this tutorial on how to call methods within the main class of a C# program. If you had any questions, please leave a comment below and one of our experts will be happy to respond. If you found this tutorial helpful, please leave a comment on your experience, we love interacting with our readers. Happy Programming!