What is the difference between ref and out parameters in C#?
Quick answer
Both pass an argument by reference, but ref requires the variable to be initialised before the call, while out requires the method to assign a value before it returns.
Use ref when the method both reads and modifies the caller's variable. Use out when the method only produces a value, such as the bool TryParse(string, out int result) pattern, which lets a method return a success flag and a value together. A third modifier, in, passes by reference as read-only, useful to avoid copying large structs.
In modern C# you can often return a tuple instead ((bool ok, int value)), which is clearer than out parameters.
if (int.TryParse(input, out int number))
{
Console.WriteLine(number * 2);
}
static void AddTen(ref int x) => x += 10;
int n = 5;
AddTen(ref n); // n is now 15