Methods (also called functions) are reusable blocks of code. They help organize your program and avoid repetition.
🛠️ Defining a Method
1
2
3
4
| void SayHello()
{
Console.WriteLine("Hello!");
}
|
🚀 Calling a Method
1
| SayHello(); // Outputs: Hello!
|
📦 Methods with Parameters
1
2
3
4
5
| void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}
Greet("Sam"); // Outputs: Hello, Sam!
|
🔙 Methods with Return Values
1
2
3
4
5
| int Add(int a, int b)
{
return a + b;
}
int sum = Add(2, 3); // sum is 5
|
🎯 Why Use Methods?
- Reusability: Write once, use many times.
- Organization: Break big problems into smaller pieces.
- Debugging: Easier to find and fix bugs.
📝 Try It!
Write a method that multiplies two numbers and returns the result.
1
2
3
4
5
| int Multiply(int x, int y)
{
return x * y;
}
Console.WriteLine(Multiply(4, 5)); // 20
|
Next: Declaring and using functions in more detail!