Methods in C#
What is a Method
A method in C# is a block of code that performs a specific task.
It can receive parameters, return values, and be called from other parts of the program.
Methods are defined inside classes or structs and can be static, instance, generic, asynchronous, and more.
Instance methods
Official Documentation: Methods overview
These are methods that operate on an instance of the class. An object must be created in order to call them.
public class Calculator { public int Add(int a, int b) { return a + b; }}
var calc = new Calculator();int result = calc.Add(2, 3); // Output: 5Static Methods
Official Documentation: Static Classes and Static Class Members
They belong to the class and not to an instance. They are called directly on the class.
public class Util { public static int Double(int x) { return x * 2; }}
int result = Util.Double(4); // Output: 8Methods with return values
Official Documentation: Create C# methods that return values
They return a value after execution. The return type is specified in the signature.
public string Greeting(string name) { return $"Hello, {name}!";}Methods with optional parameters
Official Documentation: Optional arguments
They allow default values to be defined for parameters.
public void ShowMessage(string msg = "Default message") { Console.WriteLine(msg);}
ShowMessage(); // Output: Default messageShowMessage("Hello!"); // Output: Hello!Methods with params
Official Documentation: Method parameters
They allow a variable number of arguments to be passed as an array.
public int Sum(params int[] numbers) { return numbers.Sum();}
Sum(1, 2, 3, 4); // Output: 10Methods with ref and out
Official Documentation: ref and out
They allow variables to be passed by reference.
ref: the variable must be initialized beforehand.
out: the variable will be initialized inside the method.
public void Double(ref int value) { value *= 2;}
public void GenerateNumber(out int number) { number = 42;}Generic method
Official Documentation: Generic methods
It allows working with parameterized types.
public T ReturnValue<T>(T value) { return value;}
int x = ReturnValue<int>(10); // Output: 10string s = ReturnValue<string>("test"); // Output: testAsynchronous method (async)
Official Documentation: Asynchronous programming
It runs asynchronous operations with await.
public async Task<string> FetchDataAsync() { await Task.Delay(1000); return "Data received";}Lambda methods (Anonymous Function)
Official Documentation: Lambda Expressions
Inline functions that can be assigned to delegates or used in LINQ.
Func<int, int> square = x => x * x;Console.WriteLine(square(5)); // Output: 25Extension method
Official Documentation: Extension Methods
It allows adding methods to existing types without modifying the original code.
public static class Extensions { public static int Double(this int value) { return value * 2; }}
int result = 5.Double(); // Output: 10