Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Deepika SawantRank #242 · 10.2K reputationPosted Sep 15, 2025, 11:38 AM EDT
refKeywordvoid UpdateName(ref string name) { name = "UpdatedName"; } string myName = "OriginalName"; UpdateName(ref myName); Console.WriteLine(myName); // Output: UpdatedNameoutKeywordvoid GetCoordinates(out int x, out int y) { x = 10; y = 20; } int x, y; GetCoordinates(out x, out y); Console.WriteLine($"X: {x}, Y: {y}"); // Output: X: 10, Y: 20refoutSandhiya PriyaRank #26 · 43.2K reputationPosted Oct 13, 2025, 3:05 AM EDT
Difference Between
refandoutin C#Both
refandoutkeywords allow you to pass arguments by reference to a method, meaning the method can modify the original variable. However, they have key differences:refoutvoid MyMethod(ref int x)void MyMethod(out int x)Example of
refvoid Increment(ref int number) { number += 5; // modifies original variable } int a = 10; Increment(ref a); Console.WriteLine(a); // Output: 15amust be initialized before passing to the method.Example of
outvoid GetValues(out int x, out int y) { x = 100; // must assign before returning y = 200; } int p, q; GetValues(out p, out q); Console.WriteLine($"p = {p}, q = {q}"); // Output: p = 100, q = 200pandqdon’t need initialization before the method call, but the method must assign values.Key Points
Use
refwhen the variable already has a value and you want to pass it by reference.Use
outwhen the method needs to return multiple values or initialize a variable.