wasAsked.

Difference between ref and out? Where have you used them in your project?

Impetus · Role not specified · technical

Published

Year not specified · C#

Community answers

Posted by wasAsked editorial collection

ref requires the caller to initialize a variable before the call, and the method may read or replace it. out does not require initialization, and the method must assign it before returning. Example: static void AddTax(ref decimal total) => total *= 1.18m; static bool TryRead(string text, out int value) => int.TryParse(text, out value); decimal total = 100m; AddTax(ref total); if (TryRead("42", out var count)) { /* use count */ } Use out for Try-pattern results. Prefer normal return values, tuples, or immutable result objects when several values must be returned; ref/out create mutation that is harder to reason about.

Backbencher Developer · · 0 likes

Sign in to add your answer

Related interview topics