Methods are reusable blocks of code that perform specific tasks.
static int Add(int a, int b) {
return a + b;
}
static void Greet(string name) {
Console.WriteLine($"Hello, {name}!");
}
// Calling methods
int sum = Add(5, 3);
Greet("Alice");
// ref - must be initialized before passing
void Double(ref int num) { num *= 2; }
int value = 5;
Double(ref value); // value becomes 10
// out - must be assigned inside the method
void TryParse(string s, out int result) {
result = int.TryParse(s, out int r) ? r : 0;
}
// in - read-only reference
void Display(in int num) {
Console.WriteLine(num);
}
static int Add(int a, int b) => a + b;
static double Add(double a, double b) => a + b;
static int Add(int a, int b, int c) => a + b + c;
static int Square(int x) => x * x;
static void Print(string msg) => Console.WriteLine(msg);
Write a C# program that applies the concepts covered in this chapter. Experiment with different inputs and test your understanding.