Read the syntax
ref passes an initialized variable by reference, while out lets a method assign a result without requiring prior initialization. Both modifiers are visible at the call site. Use a .NET 8+ console project; replace Program.cs with this C# example.
Increment mutates the caller’s integer variable. TryParse assigns parsed and separately returns whether conversion succeeded.
Syntax
void Increment(ref int value); bool TryParse(string text, out int value)Examples
ref and out Parameters
Use a .NET 8+ console project; replace Program.cs with this C# example.
using System;
static void Increment(ref int value) { value++; }
int count = 4;
Increment(ref count);
Console.WriteLine(count);
if (int.TryParse("42", out int parsed)) Console.WriteLine(parsed);- Expected output: 5 42
- Increment mutates the caller’s integer variable. TryParse assigns parsed and separately returns whether conversion succeeded.
- Use return values or tuples when they express the API more clearly.
Best practices
- Use return values or tuples when they express the API more clearly.
- Read an out result according to the method’s success contract.
Runtime & versions
.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
C# language reference