#csharp #dotnet #backend

Day 4: Methods & Parameters

Welcome to Day 4!

Having giant blocks of code in a single file makes it impossible to maintain. We solve this by breaking code up into Methods (functions).

Defining a Method

A method needs a return type, a name, and optional parameters.

// [Return Type] [Name]([Parameters...])
int Add(int a, int b) 
{
    return a + b;
}

// Void means it returns nothing
void GreetUser(string name) 
{
    Console.WriteLine($"Welcome back, {name}!");
}

// Usage
int sum = Add(5, 10);
GreetUser("Alice");

Expression-Bodied Methods

If your method is only doing one thing (like returning a simple calculation), you can use the => (fat arrow) syntax to make it a one-liner:

int Multiply(int x, int y) => x * y;

Parameters: Default and Named

You can provide default values for parameters, making them optional for the caller.

void PrintTicket(decimal price, bool isVIP = false) 
{
    Console.WriteLine($"Price: {price}, VIP Access: {isVIP}");
}

// Calling it
PrintTicket(50.0m); // isVIP defaults to false

You can also use Named arguments when calling the method. This makes the code much more readable, especially if you have a lot of boolean parameters.

// Notice how clear this makes the method call!
PrintTicket(price: 150.0m, isVIP: true);

Passing by Reference (ref and out)

Normally, when you pass a variable into a method, C# passes a copy of it. Modifying it inside the method doesn’t change the original variable.

If you want the method to modify the original variable, you can pass it by reference.

out parameter

Used heavily for methods that need to return multiple pieces of data. The method must assign a value to it before returning. int.TryParse from Day 2 is a famous example.

void GetDateInfo(out int month, out int year) 
{
    // We are forcing values INTO these variables
    month = 11;
    year = 2025;
}

GetDateInfo(out int m, out int y);
Console.WriteLine($"Month: {m}, Year: {y}");

Challenge for Day 4

Create a method named CalculateDiscount that takes a decimal price and an optional decimal discountPercentage (default to 10%). Have it use expression-bodied syntax (the fat arrow => ) to return the final price.

Tomorrow: Classes and Object-Oriented Programming starts.