Methods

Lesson 12
Author : Afrixi
Last Updated : February, 2023
C# - Programming Language
This course covers the basics of programming in C#.

Methods are blocks of code that perform a specific task. In C#, you define a method by specifying its name, return type (if any), and parameters (if any). Here’s an example of a simple method that takes two integers as parameters and returns their sum:


int AddNumbers(int num1, int num2)
{
    int sum = num1 + num2;
    return sum;
}

In this example, we’ve defined a method called “AddNumbers” that takes two integers as parameters (num1 and num2) and returns their sum. Inside the method, we’ve declared a local variable called “sum” and assigned it the value of adding num1 and num2 together using the + operator. We then return the value of sum.

To call this method, we would do something like this:


int result = AddNumbers(5, 10);

In this example, we’re calling the “AddNumbers” method and passing in the values 5 and 10 as arguments. The method returns the sum of these two numbers, which we’re storing in the variable “result”.

You can also define methods with no parameters or no return type. Here’s an example of a method with no parameters that simply prints a message to the console:


void PrintMessage()
{
    Console.WriteLine("Hello, world!");
}

In this example, we’ve defined a method called “PrintMessage” that takes no parameters and has no return type (specified by the void keyword). Inside the method, we’re using the Console.WriteLine() method to print the message “Hello, world!” to the console.

To call this method, we would simply do this:


PrintMessage();

In this example, we’re calling the “PrintMessage” method with no arguments. The method simply prints the message to the console and returns nothing.