Defining Methods in C#
Method syntax, return types, parameters, and the difference between passing by value and by reference.
2 min read
A method in C# is a named, reusable block of code with a declared return type and parameter list:
static int Add(int a, int b)
{
return a + b;
}
int result = Add(3, 4); // 7Every method states its return type up front (int here), or void if it doesn't return anything:
static void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}Expression-bodied methods
For a method that's just a single expression, C# offers a shorter syntax using =>:
static int Add(int a, int b) => a + b;This is functionally identical to the version with { return a + b; } — it's purely a more compact way to write a one-line method, and you'll see it used heavily for small helpers and property getters alike.
Parameters: by value vs. by reference
By default, arguments are passed by value — the method gets a copy:
static void Increment(int x)
{
x++;
}
int number = 5;
Increment(number);
Console.WriteLine(number); // still 5 -- the copy was incremented, not the originalTo let a method modify the caller's variable, use ref:
static void Increment(ref int x)
{
x++;
}
int number = 5;
Increment(ref number);
Console.WriteLine(number); // 6ref must appear at both the method definition and the call site — C# deliberately makes this visible at the call site so it's never a silent surprise.
out parameters
out is similar to ref but is meant for a method to produce a value the caller didn't need to initialize first — the classic example is TryParse:
static bool TryDivide(int a, int b, out int result)
{
if (b == 0)
{
result = 0;
return false;
}
result = a / b;
return true;
}
if (TryDivide(10, 2, out int quotient))
{
Console.WriteLine(quotient); // 5
}This "try" pattern — return a bool for success, hand back the real value via out — is idiomatic C# and shows up throughout the standard library (int.TryParse, Dictionary.TryGetValue, and more). It lets you handle a fallible operation without exceptions for what's really just an expected outcome, not an error.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.