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"
);
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.