Methods in C# define reusable blocks of behaviour. Every method belongs to a class and has a return type, a name, and parameters.
Basic Method
CSHARP
class Calculator
{
static int Add(int a, int b)
{
return a + b;
}
}
Console.WriteLine(Calculator.Add(3, 4)); // 7| Part | Meaning |
|---|---|
static |
Belongs to the class, not an instance — call it without new |
int |
Return type — the method returns an integer |
Add |
Method name — PascalCase |
(int a, int b) |
Parameters — each has a type and name |
Expression-Bodied Methods
For one-liners, use => instead of { }:
CSHARP
static int Square(int n) => n * n;
static string Greet(string name) => $"Hello, {name}!";Parameters
Default Parameters
CSHARP
static void Greet(string name, string greeting = "Hello")
{
Console.WriteLine($"{greeting}, {name}!");
}
Greet("Sita"); // "Hello, Sita!"
Greet("Sita", "Namaste"); // "Namaste, Sita!"Named Arguments
Call methods in any order by naming the arguments:
CSHARP
Greet(greeting: "Namaste", name: "Sita");Pass by Reference
CSHARP
static void Double(ref int number)
{
number *= 2; // modifies the original variable
}
int x = 5;
Double(ref x);
Console.WriteLine(x); // 10out Parameters
Return multiple values without creating a class:
CSHARP
static bool TryParse(string input, out int result)
{
try
{
result = int.Parse(input);
return true;
}
catch
{
result = 0;
return false;
}
}
if (TryParse("42", out int number))
{
Console.WriteLine($"Parsed: {number}"); // 42
}params (Variadic)
Accept any number of arguments:
CSHARP
static int Sum(params int[] numbers)
{
int total = 0;
foreach (int n in numbers)
total += n;
return total;
}
Sum(1, 2, 3); // 6
Sum(1, 2, 3, 4, 5); // 15Static vs Instance Methods
CSHARP
class MathHelper
{
// Static: called on the class itself
public static double Pi => 3.14159;
// Instance: called on an object
public double CircleArea(double radius)
{
return Pi * radius * radius;
}
}
// Static — no object needed
double pi = MathHelper.Pi;
// Instance — need an object
var helper = new MathHelper();
double area = helper.CircleArea(5);Async Methods
For asynchronous operations (network, file, database):
CSHARP
async Task<string> FetchDataAsync(string url)
{
using var client = new HttpClient();
return await client.GetStringAsync(url);
}
// Calling it
string data = await FetchDataAsync("https://api.example.com");Method Overloading
Same name, different parameter types:
CSHARP
static int Add(int a, int b) => a + b;
static double Add(double a, double b) => a + b;
Add(3, 4); // 7 (int version)
Add(3.14, 2.71); // 5.85 (double version)Tips
- Use
staticfor utility methods that do not depend on object state. - Use
async/awaitfor any I/O operation — never block with.Resultor.Wait(). - Prefer
outvariables in the calling code:if (TryParse("42", out var n)). - Keep methods short — if a method does more than one thing, split it.
Next: classes & objects — the building blocks of C#.