C# – Methods

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

The name of the method, surrounded by parenthesis (), defines a method. You are already familiar with some of the pre-defined methods that C# offers, including Main() , but you may also write your own methods to carry out certain tasks:

Example

Create a method inside the Program class:
 

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.
Remark: To make the code easier to read, it is recommended that methods in C# have their names begin with an uppercase letter.


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

static void MyMethod()
    {
      Console.WriteLine(“I just got executed!”);
    }
 
    static void Main(string[] args)
    {
      MyMethod();
      MyMethod();
      MyMethod();
    }
   //I just got executed!
 //I just got executed!
 // I just got executed!

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

An argument is a parameter that is supplied to a method. Thus, fname is a parameter while Jenny, Anja, and Liam are arguments in the example above.

Multiple Parameters

You are free to include as many parameters as you wish; simply comma-separate them:

Example

    static void MyMethod(string fname, int age)
    {
      Console.WriteLine(fname + ” is ” + age);
    }
    static void Main(string[] args)
    {
      MyMethod(“Liam”, 5);
      MyMethod(“Jenny”, 8);
      MyMethod(“Anja”, 31);
    }
 //Liam is 5
//Jenny is 8
//Anja is 31
 
Note that when you are working with multiple parameters, the method call must have the same number of arguments as there are parameters, and the arguments must be supplied in the same sequence.

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

static void MyMethod(string country = “Norway”)
    {
      Console.WriteLine(country);
    }
    static void Main(string[] args)
    {
      MyMethod(“Sweden”);
      MyMethod(“India”);
      MyMethod();
      MyMethod(“USA”);

// Sweden

//India

//Norway

//USA

“Optional parameter” is a term frequently used to describe a parameter having a default value. From the sample above, nation is an optional parameter and “Norway” is the default value.

Return Values

All of the examples on the preceding page used the void keyword, which denotes that the method shouldn’t return a value.

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

    static int MyMethod(int x)
    {
      return 5 + x;
    }

    static void Main(string[] args)
    {
      Console.WriteLine(MyMethod(3));
    }
  //Outputs 8 (5 + 3)

The two parameters of a method are added together in this example:

Example

static int MyMethod(int x, int y)
    {
      return x + y;
    }

    static void Main(string[] args)
    {
      Console.WriteLine(MyMethod(5, 3));
    }
  //Outputs 8 (5 + 3)

The outcome can also be kept in a variable, which is advised because it is simpler to understand and manage:

Example

static int MyMethod(int x, int y)
    {
      return x + y;
    }

    static void Main(string[] args)
    {
      int z = MyMethod(5, 3);
      Console.WriteLine(z);
    }
  / / Outputs 8 (5 + 3)

Named Arguments

Sending arguments using the key: value syntax is also feasible.


In this manner, it is irrelevant which arguments come first:

Example

    static void MyMethod(string child1, string child2, string child3)
    {
      Console.WriteLine(“The youngest child is: ” + child3);
    }

    static void Main(string[] args)
    {
      MyMethod(child3: “John”, child1: “Liam”, child2: “Liam”);
    }
 / / The youngest child is: John

Method Overloading

Multiple methods with distinct parameters that share the same name can occur due to method overloading:

Example

int MyMethod(int x)
float MyMethod(float x)
double MyMethod(double x, double y)

Consider the following example, which have two methods that add numbers of different type:

Example

static int PlusMethodInt(int x, int y)
    {
      return x + y;
    }

    static double PlusMethodDouble(double x, double y)
    {
      return x + y;
    }

    static void Main(string[] args)
    {
      int myNum1 = PlusMethodInt(8, 5);
      double myNum2 = PlusMethodDouble(4.3, 6.26);
      Console.WriteLine(“Int: ” + myNum1);
      Console.WriteLine(“Double: ” + myNum2);
    }  

It is preferable to overload one method rather than defining two that should accomplish the same task.


The PlusMethod method is overloaded in the example below to support both int and double data types:

Example

static int PlusMethod(int x, int y)
    {
      return x + y;
    }

    static double PlusMethod(double x, double y)
    {
      return x + y;
    }

    static void Main(string[] args)
    {
      int myNum1 = PlusMethod(8, 5);
      double myNum2 = PlusMethod(4.3, 6.26);
      Console.WriteLine(“Int: ” + myNum1);
      Console.WriteLine(“Double: ” + myNum2);
    }  
It should be noted that as long as the quantity and/or kind of parameters vary, several methods can share the same name.