A method is a code block that contains a series of statements. It is a basic part of a program and can solve a certain problem.
In C#, every executed instruction is performed in the context of a method. A typical example of a method is the already known method Main()
.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to C# Tutorial.");
}
}
The Main
method is the entry point for every C# application and it's called by the common language runtime (CLR) when the program is started.
A method can be declared in a class, struct, or interface by specifying the following;
public
or private
.abstract
or sealed
.These parts together are the signature of the method.
public virtual int Drive(int miles, int speed)
{
/* Method statements here */
return 1;
}
It is recommended, when declaring a method, to follow the rules for method naming suggested by Microsoft.
These rules are not mandatory, but recommendable, here are some examples for well-named methods.
Print
GetName
PlayMusic
SetUserName
The method may need additional information, which depends on the environment in which the method executes. The method definition specifies the names and types of any parameters that are required.
public int Add(int a, int b)
{
return a + b;
}
public int Subtract(int a, int b)
{
return a - b;
}
public void Caller()
{
int numA = 4;
int numB = 32;
int result1 = Add(numA, numB);
int result2 = Subtract(numA, numB);
Console.WriteLine(result1);
Console.WriteLine(result2);
}
All the examples related to the methods are available in the Methods.cs
file of the source code. Download the source code and try out all the examples for better understanding.