Method Basics
What Is a Method
A method is a block of code that performs a specific task. Encapsulating repeated logic into methods improves code reusability and readability.
In C#, methods must be defined inside a class or struct, unlike standalone functions in C. When using top-level statements, you can define local functions.
Method Definition and Invocation
Syntax
access_modifier return_type method_name(parameter_list)
{
method_body
}
Example
using System;
class Program
{
static void SayHello()
{
Console.WriteLine("Hello, World!");
}
static void Main()
{
SayHello();
SayHello();
}
}
Hello, World!
Hello, World!
method_name(arguments). A method only needs to be defined once and can be called multiple times.
Parameters and Return Values
Methods with Parameters
Parameters allow a method to receive data from outside, enabling it to process different inputs.
Example
using System;
class Program
{
static void Greet(string name)
{
Console.WriteLine("Hello, " + name + "!");
}
static void Main()
{
Greet("Alice");
Greet("Bob");
}
}
Hello, Alice!
Hello, Bob!
Methods with Return Values
Return values allow a method to pass computation results back to the caller.
Example
using System;
class Program
{
static int Add(int a, int b)
{
return a + b;
}
static void Main()
{
int result = Add(3, 5);
Console.WriteLine("3 + 5 = " + result);
Console.WriteLine("10 + 20 = " + Add(10, 20));
}
}
3 + 5 = 8
10 + 20 = 30
Formal and Actual Parameters
| Concept | Description | Example |
|---|---|---|
| Formal parameter | Parameters in the method definition | a, b in static int Add(int a, int b) |
| Actual parameter | Values passed when calling the method | 3, 5 in Add(3, 5) |
The return Statement
The return statement serves two purposes:
- Return a result to the caller
- Immediately exit the method — subsequent code is not executed
Example
using System;
class Program
{
static string GetGrade(int score)
{
if (score >= 90)
return "Excellent";
if (score >= 60)
return "Pass";
return "Fail";
}
static int Max(int a, int b)
{
if (a > b)
return a;
else
return b;
}
static void Main()
{
Console.WriteLine(GetGrade(95));
Console.WriteLine(GetGrade(70));
Console.WriteLine(GetGrade(45));
Console.WriteLine("Larger: " + Max(12, 8));
}
}
Excellent
Pass
Fail
Larger: 12
return is executed, the method ends immediately. In non-void methods, all code paths must return a value.
void Methods
void indicates that a method has no return value. void methods do not require a return statement, but you can use return; to exit early.
Example
using System;
class Program
{
static void PrintLine(int length)
{
if (length <= 0)
return;
string line = new string('-', length);
Console.WriteLine(line);
}
static void PrintInfo(string name, int age)
{
Console.WriteLine("Name: " + name);
Console.WriteLine("Age: " + age);
}
static void Main()
{
PrintInfo("Alice", 18);
PrintLine(20);
PrintLine(-5);
}
}
Name: Alice
Age: 18
--------------------
return; in a void method is only used for early exit and does not return any value.
The Method Call Stack
The call stack is the memory management mechanism used when a program executes methods. Each time a method is called, a stack frame is pushed onto the stack; when the method returns, the frame is popped.
Example
using System;
class Program
{
static int Square(int x)
{
return x * x;
}
static int SumOfSquares(int a, int b)
{
int sa = Square(a);
int sb = Square(b);
return sa + sb;
}
static void Main()
{
int result = SumOfSquares(3, 4);
Console.WriteLine("Result: " + result);
}
}
Result: 25
The call process is as follows:
1. Main() pushed onto stack
2. SumOfSquares(3, 4) pushed onto stack
3. Square(3) pushed → returns 9 → popped
4. Square(4) pushed → returns 16 → popped
5. SumOfSquares returns 25 → popped
6. Main → outputs 25 → popped
ℹ️ The stack follows the "last in, first out" principle. The deeper the method nesting, the more stack frames there are. Stack space is limited; excessive recursion can cause a stack overflow.
Method Naming Conventions
C# method naming uses PascalCase: the first letter of each word is capitalized, with no underscores.
| Style | Example | Language |
|---|---|---|
| PascalCase | CalculateTotal, GetUserName |
C# |
| snake_case | calculate_total, get_user_name |
C, Python |
Example
using System;
class Program
{
static double CalculateArea(double radius)
{
return 3.14159 * radius * radius;
}
static bool IsValidAge(int age)
{
return age >= 0 && age <= 150;
}
static void PrintUserInfo(string name, int age)
{
Console.WriteLine(name + ", age " + age);
}
static void Main()
{
double area = CalculateArea(5.0);
Console.WriteLine("Area: " + area);
Console.WriteLine("Valid age: " + IsValidAge(25));
PrintUserInfo("Alice", 25);
}
}
Area: 78.53975
Valid age: True
Alice, age 25
✅ Method names should start with a verb or verb phrase, such as
Get,Set,Calculate,Is,
Expression-Bodied Methods
C# 6.0 introduced expression-bodied methods, using => to simplify single-line method definitions.
Example
using System;
class Program
{
static int Square(int x) => x * x;
static double CircleArea(double r) => 3.14159 * r * r;
static bool IsAdult(int age) => age >= 18;
static void Main()
{
Console.WriteLine(Square(7));
Console.WriteLine(CircleArea(3.0));
Console.WriteLine(IsAdult(20));
}
}
49
28.27431
True
=> is shorthand for a lambda expression, equivalent to { return expression; }, and only applies to single-line logic.
Pass by Value
C# uses pass by value by default: value types copy data, reference types copy the reference.
Example
using System;
class Program
{
static void TryChange(int x)
{
x = 999;
}
static void Main()
{
int num = 10;
TryChange(num);
Console.WriteLine("num = " + num);
}
}
num = 10
Multiple Return Types
Methods can return various types: int, double, string, bool, etc.
Example
using System;
class Program
{
static int GetLength(string text)
{
return text.Length;
}
static double GetAverage(int a, int b)
{
return (a + b) / 2.0;
}
static bool IsPositive(double value)
{
return value > 0;
}
static string BuildGreeting(string name)
{
return "Welcome, " + name + "!";
}
static void Main()
{
Console.WriteLine(GetLength("Hello"));
Console.WriteLine(GetAverage(3, 4));
Console.WriteLine(IsPositive(-2.5));
Console.WriteLine(BuildGreeting("Alice"));
}
}
5
3.5
False
Welcome, Alice!
❓ FAQ
static void SayHi().
Q: Can a method have multiple return statements? A: Yes, but in non-void methods, every execution path must return a value.
Q: Can a void method use return? A: Yes, use return; to exit early, but it cannot return any value.
Q: Must formal and actual parameters have the same name? A: No, they are independent variables and can have different names.
Q: Can a C# method exist outside of a class? A: No, C# methods must be inside a class or struct, but local functions can be defined within top-level statements.
📖 Summary
- A method consists of an access modifier, return type, method name, and parameter list
- Formal parameters are variables in the definition; actual parameters are values passed at the call site
returnreturns a result and exits the method; void methods have no return value- The call stack manages method execution memory, following the last-in, first-out principle
- C# method naming uses PascalCase conventions
- Expression-bodied methods
=>simplify single-line method definitions - Default pass by value: value types copy data; modifying formal parameters does not affect actual parameters
📝 Exercises
- Write a
static int Factorial(int n)method that calculates the factorial of n and returns the result - Write a
static bool IsEven(int num)method that checks whether an integer is even, using expression-bodied syntax - Write a
static void PrintMultiplicationTable(int n)method that prints the multiplication table for n (1×n through 9×n) - Write a
static string ClassifyScore(int score)method that returns "Excellent", "Good", "Pass", or "Fail" based on the score - Write a
static double CalcBMI(double weight, double height)method that calculates BMI from weight (kg) and height (m)



