There are lots of in-built methods in C# that have their own functionality like Main() method, ToUpper(), String.Compare(string, string) etc. These methods can either return a value or not, or can have parameters or not. Methods are basically created for reuse, create once and we can use many times, anywhere in our program.
Basic syntax of a method in C# is:
returnType methodName(parameterList)
For example:
// The name of this method is AddNumbers which returns a value of type int and accepts two parameters, both of type int.
int AddNumbers(int num1, int num2)
{
int sum = num1 + num2;
return sum;
}
// The name of the method is SayHello. The return type of this method is void which means it does not return any value.
// The parameter list is also empty, hence it does not accepts any parameter.
void SayHello()
{
Console.WriteLine("Hellozz!");
}
Above are some of the ways you can create your own methods with/without parameters and with/without return values. The method names are normal variable names. We cannot have C# keywords as method names. Methods can have any number of parameters but can only return single value of any data type.
Calling/Invoking a Method
A method created is of no use until it is used anywhere in your program. A method can be used if it called somewhere in your program. Let’s use above created method in our program. Below is the sample code:
// In below class, there are three methods: Main() is the in-built method, AddNumbers() and SayHello() are custom methods.
class Program
{
static void Main(string[] args)
{
// We are calling AddNumbers() method twice which indicate that we can reuse the methods.
// We are passing two parameters of int type to AddNumbers() method which will return the sum of these two numbers.
// We can use this returned value, in this case sum of two numbers, anywhere in our program.
int sum = AddNumbers(20, 40);
Console.WriteLine(sum);
Console.WriteLine(AddNumbers(10, 34));
SayHello();
}
static int AddNumbers(int num1, int num2)
{
int sum = num1 + num2;
return sum;
}
static void SayHello()
{
Console.WriteLine("Hellozz!");
}
}
