Utilizor
Contact Us

C# Methods

Evaluating code blocks using a name.

C# Methods

A method is a block of code which only runs when it is called.

You can pass data, known as parameters, into a method.

Methods are used to perform certain actions, and they are also known as functions.

Why use methods? To reuse code: define the code once, and use it many times.

Create a Method

A method is defined with the name of the method, followed by parentheses (). C# provides some pre-defined methods, which you already are familiar with, such as Main(), but you can also create your own methods to perform certain actions:

class Program
{
  static void MyMethod() 
  {
    // code to be executed
  }
}
  • MyMethod() is the name of the method
  • static means that the method belongs to the Program class and not an object of the Program class. You will learn more about objects and how to access methods through objects later in this tutorial.
  • void means that this method does not have a return value. You will learn more about return values later in this chapter

Examples

Call a Method

Calling MyMethod inside Main.

using System;

class Program
{
  static void MyMethod() 
  {
    Console.WriteLine("I just got executed!");
  }

  static void Main(string[] args)
  {
    MyMethod();
  }
}

Multiple Calls

Reusing code.

using System;

class Program
{
  static void MyMethod() 
  {
    Console.WriteLine("I just got executed!");
  }

  static void Main(string[] args)
  {
    MyMethod();
    MyMethod();
    MyMethod();
  }
}

Method with helper

Organizing code output.

using System;

class Program
{
  static void PrintHeader()
  {
      Console.WriteLine("--- Header ---");
  }

  static void Main(string[] args)
  {
    PrintHeader();
    Console.WriteLine("Content");
    PrintHeader();
  }
}