Method:
A method is a group of statements that together perform a task. Every C# program has at
least one class with a method named Main.
To use a method, you need to −
- Define the method
- Call the method
Defining Methods in C#
When you define a method, you basically declare the elements of its structure.The syntax for defining a method in C# is as follows −
<Access Specifier><Return Type><Method Name>(Parameter List) {
Method Body
}
Following are the various elements of a method −
- Access Specifier − This determines the visibility of a variable or a method from another
- class.
- Return type − A method may return a value. The return type is the data type of the
- value the method returns. If the method is not returning any values, then the return type is void.
- Method name − Method name is a unique identifier and it is case sensitive. It cannot be
- same as any other identifier declared in the class.
- Parameter list − Enclosed between parentheses, the parameters are used to pass and
- receive data from a method. The parameter list refers to the type, order, and number of the
- parameters of a method. Parameters are optional; that is, a method may contain no parameters.
- Method body − This contains the set of instructions needed to complete the required
- activity.
Calling Methods in C#
You can call a method using the name of the method. The following example illustrates this−
MethodIntroApp: Create Method and Calling Method
To make the create method and calling method more clear, we will go through a MethodIntroApp
now.
Steps:
1. Create a Console application
2. Write down the following code into the main method.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MethodIntroApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Display());
int firstNumber = 10;
int secondNumber = 20;
Console.WriteLine("Result: " + Add(firstNumber, secondNumber));
Console.ReadKey();
}
static string Display()
{
return"This is a method";
}
static int Add(int firstNumber, int secondNumber)
{
int result = firstNumber + secondNumber;
return result;
}
}
}
Build the application and run it
Tags
C#