wasAsked.

What is out and ref?

Agiliad Technologies Pvt Ltd · Role not specified · technical

Published

Asked in 2026 · C#

Community answers

Posted by wasAsked editorial collection

ref and out both pass a variable by reference, so the called method works with the caller's actual variable rather than a copy. Changes made inside the method are visible to the caller. ref - The caller must initialise the variable before passing it. - The method can read the value and may change it. - Typical use: modify an existing value. void Increase(ref int stock, int amount) => stock += amount; int stock = 10; Increase(ref stock, 5); // stock = 15 out - The variable does not need to be initialised before the call. - The method must assign a value before returning. - Typical use: return extra results, especially in Try methods. bool TryGetDiscount(string code, out decimal percent) { percent = code switch { "WELCOME10" => 10m, "FEST20" => 20m, _ => 0m }; return percent > 0; } if (TryGetDiscount("FEST20", out var discount)) Console.WriteLine($"Discount: {discount}%"); Framework examples - out: int.TryParse(text, out var value), dictionary.TryGetValue(key, out var item). - ref: Interlocked.Increment(ref counter), Array.Resize(ref array, newSize). Differences at a glance - Initialisation before the call: required for ref, not required for out. - Assignment inside the method: optional for ref, mandatory for out. - Reading inside before assignment: allowed for ref, not allowed for out. - Both keywords must be written at the call site as well, making the intent visible. Related keyword: in passes a read-only reference, useful for large structs to avoid copying without allowing modification. Restrictions - async methods, iterators (yield) and lambdas capturing them cannot use ref or out parameters. - Properties cannot be passed as ref or out (only variables, fields and array elements). Modern alternative For returning several values, tuples or records are often clearer: (bool found, decimal percent) GetDiscount(string code) => ... var (found, percent) = GetDiscount("FEST20"); Use out for the standard TryXxx pattern and ref for real in-place modification or performance needs.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics