Methods
Definition
A method in C# is a code block containing a series of statements that perform a specific task. Methods promote code reuse, readability, and modularity by encapsulating logic into named, callable units.
// Basic method
public int Add(int a, int b)
{
return a + b;
}
Core Concepts
Method Declaration
A method consists of an access modifier, return type, name, parameter list, and body:
[access modifier] [modifiers] [return type] [name]([parameters])
{
// method body
}
public static double CalculateArea(double radius)
{
return Math.PI * radius * radius;
}
- Access modifiers:
public,private,protected,internal,protected internal,private protected - Modifiers:
static,async,abstract,virtual,override,sealed,new,unsafe,extern - Return type: any type, or
voidif no value is returned
Expression-Bodied Methods (C# 6+)
Single-expression methods can use => syntax for concise declarations:
public int Double(int x) => x * 2;
public string GetFullName(string first, string last) => $"{first} {last}";
// Works for void methods too
public void Log(string message) => Console.WriteLine(message);
Parameters
Value Parameters (default)
Arguments are passed by value — the method receives a copy of the argument:
public void Increment(int x)
{
x++; // Only modifies the local copy
}
int num = 5;
Increment(num);
// num is still 5
ref Parameters
The argument is passed by reference. The method can read and modify the original variable. The variable must be initialized before the call:
public void Double(ref int x)
{
x *= 2;
}
int num = 5;
Double(ref num);
// num is now 10