Defining Methods
Defining Methods in C#
Methods encapsulate reusable logic. Every C# method lives inside a class or struct.
Access modifiers
public– accessible everywhere.private– accessible only within the containing type (default).protected– accessible within the type and its subclasses.internal– accessible within the same assembly.
Return types and void
Every method declares a return type. Use void when nothing is returned.
out and ref parameters
ref— pass a variable by reference (caller must initialize).out— pass a reference for the method to assign (caller need not initialize).
Expression-bodied methods
For single-expression methods, use the => syntax:
csharp
public int Add(int a, int b) => a + b;Key points:
- C# methods follow PascalCase naming by convention.
staticmethods belong to the type, not an instance.outparameters are commonly used in the Try-Parse pattern:int.TryParse(s, out int result).
Code Examples
Methods with out parameterscsharp
using System;
class MathUtils {
public static bool TryDivide(int dividend, int divisor, out double result) {
if (divisor == 0) { result = 0; return false; }
result = (double)dividend / divisor;
return true;
}
public static (int Min, int Max) MinMax(int[] arr) {
int min = arr[0], max = arr[0];
foreach (var n in arr) {
if (n < min) min = n;
if (n > max) max = n;
}
return (min, max);
}
static void Main() {
if (TryDivide(10, 3, out double r))
Console.WriteLine($"10 / 3 = {r:F2}");
TryDivide(5, 0, out double r2);
Console.WriteLine($"5 / 0 succeeded: false");
var (min, max) = MinMax(new[] { 3, 1, 4, 1, 5, 9 });
Console.WriteLine($"Min: {min}, Max: {max}");
}
}out parameters let a method return multiple values. Tuples are another idiomatic approach in modern C#.
Expression-bodied methodscsharp
using System;
class Geometry {
public double Radius { get; }
public Geometry(double radius) => Radius = radius;
public double Area() => Math.PI * Radius * Radius;
public double Circumference() => 2 * Math.PI * Radius;
public override string ToString() => $"Circle(r={Radius})";
static void Main() {
var c = new Geometry(5);
Console.WriteLine(c);
Console.WriteLine($"Area: {c.Area():F2}");
Console.WriteLine($"Circumference: {c.Circumference():F2}");
}
}Expression-bodied members use => for concise one-liners. They work for methods, properties, constructors, and more.
Quick Quiz
1. What is the difference between `out` and `ref` parameters?
2. What is the default access modifier for a C# class method?
Was this lesson helpful?