What is a method in C# and how do you define one?

Experience Level: Junior
Tags: C#

Answer

A method is a container containing piece of a computer program code that does something. A method encapsulates the code and allows the other parts of a computer program to run the code within a method. We say the method is being called by other code.

Once the method gets called, the code contained within the method gets executed by the computer. During the execution some result can get calculated. In the end of the method execution the calculated result can be returned to a caller. There can also be methods that don't return anything. They just do something but they don't return any result.

Each method must be placed within a class. So if you plan to define a new method, you have to create a new class first or you need to put the method to a class that already exists.

In the code below, we defined four methods and put them to the class Radio that represent our simulation of radio.

The first method is called TurnOn and when it gets executed, it turns the radio on. It doesn't return any result.

The second method is called TurnOff and when it gets executed, it turns the radio off. It doesn't any result.

The third method is called SetVolumeLevel and when it gets executed, it sets the radio volume level to a level that the caller passes. It doesn't return any result.

The fourth method is called GetVolumeLevel and when it gets executed, it gets the current radio level and returns it to the caller.
 

Example
public class Radio
{
  public void TrunOn()
  {
    // Some code here
  }
  
  public void TurnOff()
  {
    // Some code here
  }

  public void SetVolumeLevel(int volumeLevel)
  {
    // Some code here
  }
  
  public int GetVolumeLevel()
  {
    // Some code here
  }  
}

Comments

No Comments Yet.
Be the first to tell us what you think.
C# for beginners
C# for beginners

Are you learning C# ? Try our test we designed to help you progress faster.

Test yourself