A method is a code block that executes only when it is called.
Parameters are pieces of data that you can pass into a method.
Often referred to as functions, methods are employed to carry out specific tasks.
Why employ techniques? Code can be reused by defining it only once and using it repeatedly.
Create a Method
Example
class program
{
static void MyMethod()
{
// code to be executed
}
}
Example Explained
- The method’s name is MyMethod()
- If a method is static, it is not an object of the Program class but rather a member of the Program class. Later in this course, you will discover more about objects and how to access methods through them.
- A return value of void indicates that there isn’t one for this procedure. Later in this chapter, return values will be covered in greater detail.
Call a Method
Write the name of the method, two parenthesis () and a semicolon to call (run) the method;
In the example below, when MyMethod() is invoked, a text (the action) is printed:
Example
Inside Main()
, call the myMethod()
method:
static void MyMethod()
{
Console.WriteLine(“I just got executed!”);
}
static void Main(string[] args)
{
MyMethod();
}
//Outputs “I just got executed!”
A method can be called many times:
Example
C# Method Parameters
Parameters and Arguments
Methods can accept parameters that provide information. Inside the method, parameters take the role of variables.
They are described inside the parenthesis, following the name of the procedure. Add as many options as you like; commas should be used to separate them.
A method in the following example accepts a string parameter called fname. The method takes a first name as input when it is called, and uses that name to print the entire name inside the method:
Example
static void MyMethod(string fname)
{
Console.WriteLine(fname + ” Refsnes”);
}
static void Main(string[] args)
{
MyMethod(“Liam”);
MyMethod(“Jenny”);
MyMethod(“Anja”);
}
// Liam Refsnes
//Jenny Refsnes
//Anja Refsnes
Multiple Parameters
Example
Default Parameter Value
Equals (=) can also be used to set a default value for a parameter.
When the method is called without a parameter, “Norway” is used as the default value.
Example
// Sweden
//India
//Norway
//USA
Return Values
Use a primitive data type (like int or double) in place of void and the return keyword inside the method if you want the procedure to return a value:
Example
Example
The outcome can also be kept in a variable, which is advised because it is simpler to understand and manage:
Example
Named Arguments
Sending arguments using the key: value syntax is also feasible.
In this manner, it is irrelevant which arguments come first:
Example
Method Overloading
Example
Example
The PlusMethod method is overloaded in the example below to support both int and double data types: