A method is a named block of code that performs a specific task. Methods prevent code duplication and make programs easier to read and maintain.
// Syntax: accessModifier returnType MethodName(parameters)
public static int Add(int a, int b)
{
return a + b;
}
// Call it
int result = Add(3, 4); // 7
public static void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}
Greet("Alice"); // Hello, Alice!
public static int Square(int n) => n * n;
public static void Print(string s) => Console.WriteLine(s);
Console.WriteLine(Square(5)); // 25
public static int Factorial(int n)
{
return Calculate(n);
int Calculate(int x) => x <= 1 ? 1 : x * Calculate(x - 1);
}
Console.WriteLine(Factorial(5)); // 120