Functions (also called methods in C#) are essential for writing clean, reusable code.
🛠️ How to Declare a Function
1
2
3
4
int Add(int a, int b)
{
return a + b;
}
int
: Return type (the function returns an int)Add
: Function name(int a, int b)
: Parameters (inputs)
🚀 How to Call a Function
1
2
int result = Add(2, 3);
Console.WriteLine(result); // 5
📦 Functions with No Return Value
Use void
when your function doesn’t return anything:
1
2
3
4
5
void SayHello(string name)
{
Console.WriteLine($"Hello, {name}!");
}
SayHello("Alex");
📝 Why Use Functions?
- Avoid repeating code (DRY: Don’t Repeat Yourself)
- Break big problems into small pieces
- Make your program easier to read and fix
💡 Try It!
Write a function that checks if a number is even:
1
2
3
4
5
bool IsEven(int n)
{
return n % 2 == 0;
}
Console.WriteLine(IsEven(4)); // True
Next: Learn more about function parameters and return values!