C# Tutorial menu

C# Methods

A method is a block of code with a name. It runs only when you call it, and you can call it as often as you need.

Creating a Method

In a top-level program you can write methods directly below your code. Here void means the method returns nothing:

Example

csharp
PrintHeader();
Console.WriteLine("Fee: Rs 3000");
PrintHeader();

static void PrintHeader()
{
    Console.WriteLine("====================");
}
Output
====================
Fee: Rs 3000
====================

Parameters and Return Values

Example

csharp
int bill = TotalPrice(350, 4);
Console.WriteLine($"Total: Rs {bill}");
Console.WriteLine(IsPassing(45));

static int TotalPrice(int price, int quantity)
{
    return price * quantity;
}

static bool IsPassing(int marks)
{
    return marks >= 50;
}
Output
Total: Rs 1400
False
PartExampleMeaning
Return typeintThe type of value sent back
NameTotalPriceC# method names use PascalCase
Parameters(int price, int quantity)The inputs
returnreturn price * quantity;Sends the answer back

Expression-bodied Methods

A method that only returns one expression can be written with =>:

Example

csharp
static double Area(double radius) => Math.PI * radius * radius;

Optional and Named Arguments

Give a parameter a default value to make it optional. You can also pass arguments by name:

Example

csharp
Greet("Ayesha");
Greet("Hamza", "Peshawar");
Greet(city: "Quetta", name: "Zainab");

static void Greet(string name, string city = "Karachi")
{
    Console.WriteLine($"Welcome {name} from {city}");
}
Output
Welcome Ayesha from Karachi
Welcome Hamza from Peshawar
Welcome Zainab from Quetta

Method Overloading

Methods can share a name if their parameters are different:

Example

csharp
Console.WriteLine(Add(2, 3));
Console.WriteLine(Add(1.5, 2.25));

static int Add(int a, int b) => a + b;
static double Add(double a, double b) => a + b;
Output
5
3.75

Passing by Value and by ref

Normally a method gets a copy of a number. With ref, it works on the original variable:

Example

csharp
int score = 10;
AddFive(score);
Console.WriteLine(score);
AddFiveRef(ref score);
Console.WriteLine(score);

static void AddFive(int x) { x += 5; }
static void AddFiveRef(ref int x) { x += 5; }
Output
10
15

Use ref only when you really need it. A method that returns a new value is usually easier to understand than one that changes its inputs.

Exercise

Exercise

What does a method with return type void give back?

Learn C# with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp