You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Methods are the building blocks of C# programs. They encapsulate reusable logic, accept input through parameters, and return results. This lesson covers method declarations, parameter passing, overloading, and modern syntax.
A method has a return type, a name, and zero or more parameters:
// Method with return value
int Add(int a, int b)
{
return a + b;
}
// Void method (no return value)
void PrintGreeting(string name)
{
Console.WriteLine($"Hello, {name}!");
}
int sum = Add(3, 5); // 8
PrintGreeting("Alice"); // Hello, Alice!
For simple one-line methods, use the => syntax:
int Add(int a, int b) => a + b;
string Greet(string name) => $"Hello, {name}!";
void Log(string message) => Console.WriteLine($"[LOG] {message}");
void SendEmail(string to, string subject = "No Subject", int priority = 1)
{
Console.WriteLine($"To: {to}, Subject: {subject}, Priority: {priority}");
}
SendEmail("alice@example.com"); // Uses defaults
SendEmail("bob@example.com", "Meeting", 3); // All specified
SendEmail("carol@example.com", priority: 5); // Named argument
Named arguments let you specify parameters in any order:
SendEmail(
priority: 2,
to: "dave@example.com",
subject: "Urgent"
);
| Keyword | Direction | Must Initialise Before Call | Must Assign in Method |
|---|---|---|---|
| (none) | In (by value) | Yes | No |
ref | In/Out | Yes | No |
out | Out | No | Yes |
in | In (read-only ref) | Yes | No |
void Double(int x)
{
x *= 2; // Only modifies the local copy
}
int num = 5;
Double(num);
Console.WriteLine(num); // Still 5
void Double(ref int x)
{
x *= 2; // Modifies the original variable
}
int num = 5;
Double(ref num);
Console.WriteLine(num); // 10
bool TryDivide(int a, int b, out int result)
{
if (b == 0)
{
result = 0;
return false;
}
result = a / b;
return true;
}
if (TryDivide(10, 3, out int quotient))
{
Console.WriteLine($"Result: {quotient}"); // 3
}
double CalculateDistance(in Point a, in Point b)
{
// a and b are passed by reference but cannot be modified
return Math.Sqrt(Math.Pow(b.X - a.X, 2) + Math.Pow(b.Y - a.Y, 2));
}
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.