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.
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:
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:
MyMethod() is the name of the method. In C#, it is a convention to start method names with an uppercase letter (PascalCase).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 static methods later in the classes tutorial.void means that this method does not have a return value. We will explore how to return values in the next lesson.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 ;.
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.
One of the greatest advantages of methods is reusability. A method can be called as many times as you want!
using System;namespace MyApplication { class Program { static void MyMethod() { Console.WriteLine("I just got executed!"); } static void Main(string[] args) { MyMethod(); MyMethod(); MyMethod(); } } }
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:
CalculateTotal()PrintReport()GetUserAge()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.
What is the correct way to call a method named "MyMethod" in C#?