C# Methods
A method is a block of code that organizes a group of related statements together to perform a specific task. It is the core mechanism in C# for implementingCode Reuseandlogic encapsulation. Every C# program has at least one Main method as its program entry point.
Using a method requires two steps:Define a methodandCall the method。
1. Defining a Method
The basic syntax for defining a method in C# is as follows:
<访问修饰符> <返回类型> <方法名>(<参数列表>)
{
方法体
}
A method consists of the following elements:
- access modifiers(Access Modifier): controls the visibility of the method, such as
public、private、protected、internal。 - Return Type(Return Type): the data type of the method's return value. If the method returns no value, use
void。 - Method Names(Method Name): the unique identifier of the method, using PascalCase naming convention (e.g.
FindMax、GetUserName)。 - Parameter list(Parameter List): the inputs the method receives, enclosed in parentheses. Parameters are optional; a method can have no parameters.
- Method body(Method Body): contains the code that implements the functionality, enclosed in curly braces
{}for enclosure.
The following figure shows the complete structure of a method:
1.1 First Method Example
The following defines a FindMax method that takes two integers and returns the larger one:
Example
using
System
;
namespace
MethodDemo
{
class
NumberHelper
{
// Define a method: takes two ints, returns the larger one
public
int
FindMax
(
int
num1,
int
num2
)
{
if
(
num1
num2
)
return
num1
;
else
return
num2
;
}
static
void
Main
(
string
[
]
args
)
{
// Create an object and call the method
NumberHelper helper
=
new
NumberHelper
(
)
;
int
result
=
helper
.
FindMax
(
100
,
200
)
;
Console
.
WriteLine
(
$
"The maximum value is: {result}"
)
;
// The maximum value is: 200
}
}
}
The method call flow:
Calling across classes:As long as the method is declared as
public, it can be called from other classes by creating an instance. This is the basis of code reuse in object-oriented programming.
2. Parameter Passing Modes
C# provides three ways to pass parameters to methods; their core difference lies inwhether memory is shared:
| Method | The keyword | Behavior | Typical scenario |
|---|---|---|---|
| Pass by value | (none) | copies the parameter value; modifications inside the method do not affect the original variable | most method calls (default) |
| Pass by reference | ref |
passes a reference to the variable; modifications inside the method change the original variable | when you need to modify external variables (e.g., swapping values) |
| Output parameter | out |
similar to ref, but the method must assign a value and no initialization is needed before the call | when a method needs to return multiple values |
2.1 Pass by Value (Default)
Pass by value is the default mode. The value of the actual argument isCopyto the formal parameter; modifications to the formal parameter inside the method do not affect the original variable:
Example
using
System
;
namespace
ParameterDemo
{
class
Program
{
// Pass by value: x and y are copies of a and b
public
void
Swap
(
int
x,
int
y
)
{
int
temp
=
x
;
x
=
y
;
y
=
temp
;
Console
.
WriteLine
(
$
" Inside the method: x={x}, y={y}"
)
;
// Swap successful
}
static
void
Main
(
string
[
]
args
)
{
var
p
=
new
Program
(
)
;
int
a
=
100
, b
=
200
;
Console
.
WriteLine
(
$
"Before call: a={a}, b={b}"
)
;
p
.
Swap
(
a, b
)
;
Console
.
WriteLine
(
$
"After call: a={a}, b={b}"
)
;
// a and b are unchanged!
}
}
}
调用前:a=100, b=200
方法内:x=200, y=100
调用后:a=100, b=200
2.2 Pass by Reference (ref)
Use ref keyword passes thereference(memory address) of the variable; modifications to the formal parameter inside the method directly affect the original variable. Note that you must also add ref:
Example
using
System
;
namespace
ParameterDemo
{
class
Program
{
// Pass by reference: x and y directly reference the memory of a and b
public
void
Swap
(
ref
int
x,
ref
int
y
)
{
int
temp
=
x
;
x
=
y
;
y
=
temp
;
}
static
void
Main
(
string
[
]
args
)
{
var
p
=
new
Program
(
)
;
int
a
=
100
, b
=
200
;
Console
.
WriteLine
(
$
"Before call: a={a}, b={b}"
)
;
p
.
Swap
(
ref
a,
ref
b
)
;
// ref must also be added when calling
Console
.
WriteLine
(
$
"After call: a={a}, b={b}"
)
;
// Swap successful!
}
}
}
调用前:a=100, b=200
调用后:a=200, b=100
The difference between ref and out:
refrequires the variable to beinitialized before passing;outdoes not require this, but inside the methoda value must be assigned to the out parameterbefore it can be used.
2.3 Output Parameters (out)
out parameters allow a method toReturn multiple values. Unlike ref , the variable does not need to be initialized before the call, but the method must assign it a value:
Example
using
System
;
namespace
ParameterDemo
{
class
Program
{
// out parameter: the method is responsible for assigning a value
public
void
GetValues
(
out
int
x,
out
int
y
)
{
Console
.
Write
(
"Please enter the first value: "
)
;
x
=
Convert
.
ToInt32
(
Console
.
ReadLine
(
)
)
;
Console
.
Write
(
"Please enter the second value: "
)
;
y
=
Convert
.
ToInt32
(
Console
.
ReadLine
(
)
)
;
// Note: all out parameters must be assigned before the method ends, otherwise a compile error occurs
}
// Practical example: the TryParse pattern
public
bool
TryDivide
(
int
a,
int
b,
out
double
result
)
{
if
(
b
==
0
)
{
result
=
0
;
return
false
;
// divisor is zero
}
result
=
(
double
)
a
/
b
;
return
true
;
}
static
void
Main
(
string
[
]
args
)
{
var
p
=
new
Program
(
)
;
// out parameter needs no initialization
int
a, b
;
p
.
GetValues
(
out
a,
out
b
)
;
Console
.
WriteLine
(
$
"a={a}, b={b}"
)
;
// TryParse pattern
if
(
p
.
TryDivide
(
10
,
3
,
out
double
res
)
)
Console
.
WriteLine
(
$
"10 / 3 = {res:F2}"
)
;
// 3.33
}
}
}
Since C# 7.0, you candeclare inline out variables at the call site, making the code more concise:
// C# 7.0+ 内联声明
if (int.TryParse("123", out int number))
Console.WriteLine($"解析成功:{number}");
3. Recursive Methods
Recursion refers to a methodCall itself. Every recursive method requires two elements:
- Base case(Base Case): the condition that terminates recursion, preventing infinite recursion
- Recursive step(Recursive Step): breaking the problem down into smaller subproblems
Classic example — calculating factorial $$n! = n \times (n-1)!$$:
Example
using
System
;
namespace
RecursionDemo
{
class
Program
{
// Recursively calculate factorial
public
int
Factorial
(
int
n
)
{
// Base case: 0! = 1, 1! = 1
if
(
n
<=
1
)
return
1
;
// Recursive step: n! = n × (n-1)!
return
n
Factorial
(
n
1
)
;
}
static
void
Main
(
string
[
]
args
)
{
var
p
=
new
Program
(
)
;
Console
.
WriteLine
(
$
"6! = {p.Factorial(6)}"
)
;
// 720
Console
.
WriteLine
(
$
"7! = {p.Factorial(7)}"
)
;
// 5040
Console
.
WriteLine
(
$
"8! = {p.Factorial(8)}"
)
;
// 40320
}
}
}
6! = 720
7! = 5040
8! = 40320
The expansion process of recursive calls:
Factorial(4)
= 4 × Factorial(3)
= 4 × 3 × Factorial(2)
= 4 × 3 × 2 × Factorial(1)
= 4 × 3 × 2 × 1
= 24
Note:Excessive recursion depth can lead to
StackOverflowException. For performance-sensitive scenarios, consider using a loop instead.
4. More Method Features
4.1 Default Parameters and Named Parameters
C# allows settingDefault valuefor parameters, which can be omitted when calling. Combined withnamed parameters, you can also skip some parameters and specify only the later ones:
Example
using
System
;
namespace
MethodFeatures
{
class
Program
{
// Default parameter: power defaults to 2
static
double
Power
(
double
baseNum,
int
power
=
2
)
{
double
result
=
1
;
for
(
int
i
=
0
;
i
<
power
;
i
++
)
result
*=
baseNum
;
return
result
;
}
// Multiple default parameters
static
void
PrintInfo
(
string
name,
int
age
=
18
,
string
city
=
"File %s type is: %s%n"
)
{
Console
.
WriteLine
(
$
"{name}, {age} years old, {city}"
)
;
}
static
void
Main
(
string
[
]
args
)
{
// Use default parameters
Console
.
WriteLine
(
Power
(
3
)
)
;
// 9.0 (using default power=2)
Console
.
WriteLine
(
Power
(
3
,
3
)
)
;
// 27.0
// Named parameter: skip age, specify only city
PrintInfo
(
"Xiao Ming"
, city
:
"Beijing"
)
;
// Output: Xiaoming, 18 years old, Beijing
// Named parameters can be out of order
PrintInfo
(
city
:
"Shanghai"
, name
:
"Xiao Hong"
, age
:
25
)
;
// Output: Xiaohong, 25 years old, Shanghai
}
}
}
4.2 Expression-bodied Methods
When the method body has only one statement, you can use => a simplified form (C# 6.0+):
// 传统写法
public int Add(int a, int b)
{
return a + b;
}
// Expression body syntax (equivalent)
public int Add(int a, int b) => a + b;
4.3 Method Overloading
A single class can havemultiple methods with the same name, as long as the parameter lists differ (different parameter types, counts, or orders):
Example
using
System
;
namespace
MethodFeatures
{
class
Calculator
{
// Overload 1: add two ints
public
int
Add
(
int
a,
int
b
)
=>
a
b
;
// Overload 2: add three ints
public
int
Add
(
int
a,
int
b,
int
c
)
=>
a
b
c
;
// Overload 3: add two doubles
public
double
Add
(
double
a,
double
b
)
=>
a
b
;
static
void
Main
(
string
[
]
args
)
{
var
calc
=
new
Calculator
(
)
;
Console
.
WriteLine
(
calc
.
Add
(
1
,
2
)
)
;
// 3 (calls overload 1)
Console
.
WriteLine
(
calc
.
Add
(
1
,
2
,
3
)
)
;
// 6 (calls overload 2)
Console
.
WriteLine
(
calc
.
Add
(
1.5
,
2.5
)
)
;
// 4.0 (calls overload 3)
}
}
}
Summary
| Feature | Syntax | Description |
|---|---|---|
| Define a method | int Add(int a, int b) { ... } |
Specify the return type, method name, and parameters |
| no return value | void DoSomething() { ... } |
void indicates no value is returned |
| Pass by value | void Foo(int x) |
default mode; modifying formal parameters does not affect actual arguments |
| Pass by reference | void Foo(ref int x) |
shared memory; modifications are reflected in actual arguments |
| Output parameter | void Foo(out int x) |
the method must assign a value; can return multiple values |
| Default arguments | void Foo(int x = 10) |
can be omitted when calling, using the default value |
| named parameters | Foo(city: "北京") |
specify parameters by name, can be out of order |
| Expression body | int Add(int a, int b) => a + b; |
shorthand for a single-line method (C# 6.0+) |
| Method overloading | same name, different parameters | the compiler automatically selects based on the parameter list |