Published on: June 4, 2025
Category: Code Snippet/Tip Day
Tags: C#, ref keyword, out keyword, in keyword, .NET Tips, C# Parameters, .NET Dev Corner
π§ What are ref
, out
, and in
?
Keyword | Behavior | Requirement | Use Case |
---|---|---|---|
ref |
Passes a reference; can read & write | Must be initialized before passing | Modify the input and return a result |
out |
Outputs a value from a method | Does not need to be initialized before | Return multiple values from a method |
in |
Read-only reference | Must be initialized before passing | Pass large structs without copying |
π ref
Example
void AddTen(ref int number)
{
number += 10;
}
int myValue = 5;
AddTen(ref myValue);
Console.WriteLine(myValue); // Output: 15
π out
Example
bool TryDivide(int dividend, int divisor, out int result)
{
if (divisor == 0)
{
result = 0;
return false;
}
result = dividend / divisor;
return true;
}
int answer;
if (TryDivide(10, 2, out answer))
Console.WriteLine($"Result: {answer}"); // Output: 5
π in
Example
void PrintPoint(in Point p)
{
Console.WriteLine($"X: {p.X}, Y: {p.Y}");
}
readonly struct Point
{
public int X { get; }
public int Y { get; }
public Point(int x, int y) => (X, Y) = (x, y);
}
var point = new Point(5, 10);
PrintPoint(in point);
π Summary Table
Use This | When You Need To… |
---|---|
ref |
Modify a parameter and retain changes |
out |
Return a value via parameter (often alongside return) |
in |
Pass read-only struct efficiently |
π§ Pro Tip
- Avoid excessive use of
ref
andout
in public APIs—use tuples or objects instead. - Use
in
with large value types to improve performance.
π¬ Stay Connected
- π Blog: www.ajaygangwar.com
- πΌ LinkedIn: Ajay Gangwar
- π§ Email: seajaygangwar@gmail.com