Methods

Methods

Functions are called Methods in C#, they are segments of a larger program that perform specific tasks:

  • They can be used to keep code clean by separating it into small and manageable pieces of code.

  • They can also be used in more than one place allowing you to reuse previous code.

Methods in C# are defined like this:

Syntax

modifier1 modifier2 type Name ( parameter 1, parameter 2 ...)
{
  //code
  return value;
}

Example

public static int Multiply(int a, int b)
{
  //code...  
  return a * b;

}

We will talk about modifier1 and modifier2 soon, for now we can use public and static respectively. In case the method does not return any value back, in place of type, we use the word void

Exercise

Write a method that adds two numbers (provided as parameters). Tip: you will need to use the modifiers public and static.

Expectation

2
3
5
using System;

public class Methods
{
    public static void Main()
    {
        int x = Convert.ToInt32(Console.ReadLine());
        int y = Convert.ToInt32(Console.ReadLine());
        int a = Add(x,y);
        Console.WriteLine(a);
    }

    //your code below:
}

Last updated