C# Methods

C# Methods: Reusing Your Code

A method (also known as a function in other programming languages) is a block of code which only runs when it is called. You can pass data, known as parameters, into a method, and it can also return data back to you.

Methods are fundamental to object-oriented programming in C#. They allow you to organize your code into manageable, reusable pieces.


1. Why Use Methods?

Imagine writing a program that needs to calculate the area of a circle in five different places. Instead of writing the same calculation formula five times, you can write it once inside a method, and simply call that method whenever you need it.

Using methods provides several major benefits:


2. How to Create a Method

A method must be declared within a class. It 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.

Here is the basic syntax for creating a method:

class Program
{
    static void MyMethod() 
    {
        // code to be executed
    }
}

Let's break down what this means:


3. How to Call a Method

Creating a method just tells the program what the method does. To actually execute the code inside the method, you must call it.

To call a method in C#, write the method's name followed by two parentheses () and a semicolon ;.

Example: Creating and Calling a Method

using System;

namespace MyApplication { class Program { static void MyMethod() { Console.WriteLine("I just got executed!"); } static void Main(string[] args) { // Calling the method MyMethod(); } } }

When the program runs, it starts executing the Main method. When it reaches MyMethod();, it jumps to the MyMethod block, executes the Console.WriteLine statement, and then returns to the Main method to continue execution.


4. Calling a Method Multiple Times

One of the greatest advantages of methods is reusability. A method can be called as many times as you want!

Example: Calling a Method Multiple Times

using System;

namespace MyApplication { class Program { static void MyMethod() { Console.WriteLine("I just got executed!"); } static void Main(string[] args) { MyMethod(); MyMethod(); MyMethod(); } } }


5. Method Naming Conventions

When naming your methods in C#, it is highly recommended to follow the PascalCase naming convention. This means the first letter of every word in the method name should be capitalized.

Good Examples:

Pro Tip: Method names should ideally be verbs or verb phrases because methods perform actions. A name like `CalculateTotal` clearly communicates what the method does, whereas a name like `TotalAmount` sounds like a variable holding data.


Exercise

?

What is the correct way to call a method named "MyMethod" in C#?