Methods
Prerequisites: Arrays
Syntax
static int Add(int a, int b) {
return a + b;
}
static void Greet(string name) {
Console.WriteLine($"Hello, {name}");
}
Example
static int Square(int n) => n * n; // expression-bodied method
Console.WriteLine(Square(4));
Expected output
16
=> (an expression body) is shorthand for a method whose
entire body is a single return expression — used constantly in
idiomatic C# for short methods.
Common mistakes
- Method and parameter names by convention use
PascalCasein C# (GetBalance, notgetBalanceas in Java) — mixing conventions from another language is a common giveaway in C# code review.
Practice
Write a method IsEven(int n) that returns true if n is even,
as an expression-bodied method.
Show solution
static bool IsEven(int n) => n % 2 == 0;