C# Methods

The method is a code block that only works when called.

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

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

Why should you use methods? Code reset: define code once, and use it multiple times.


Create a Method

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

Example

Create a method inside the Program class:

class Program
            {
              static void MyMethod() 
              {
                // code to be executed
              }
            }
Example Explained
  • MyMethod() is a domain name
  • static means that the method belongs to the Program category and not to the Program category. You will learn more about objects and how to access methods by using objects later in this lesson.
  • void means that this method has no return value. You will learn more about the return values ​​later in this chapter

Call a Method

To drive (remove) a path, type the path of the path followed by two parentheses () and a semicolon;

In the following example, MyMethod () is used to print text (action), if it is called:

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!"
            

The method can be called multiple 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!