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
PrintHeader();
Console.WriteLine("Fee: Rs 3000");
PrintHeader();
static void PrintHeader()
{
Console.WriteLine("====================");
}==================== Fee: Rs 3000 ====================
Parameters and Return Values
Example
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;
}Total: Rs 1400 False
| Part | Example | Meaning |
|---|---|---|
| Return type | int | The type of value sent back |
| Name | TotalPrice | C# method names use PascalCase |
| Parameters | (int price, int quantity) | The inputs |
return | return price * quantity; | Sends the answer back |
Expression-bodied Methods
A method that only returns one expression can be written with =>:
Example
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
Greet("Ayesha");
Greet("Hamza", "Peshawar");
Greet(city: "Quetta", name: "Zainab");
static void Greet(string name, string city = "Karachi")
{
Console.WriteLine($"Welcome {name} from {city}");
}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
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;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
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; }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?
