Ref in .NET Core
๐ Ref in .NET Core
The ref keyword in C# allows you to pass a variable by reference, meaning the method can modify the original value—not just a copy.
๐ Basic Syntax
public void SomeMethod(ref int number)
{
number = number * 2;
}
In this example, the value of number will be modified both inside and outside the method because it's passed by reference.
๐งช Practical Example
public class RefExample
{
public void DoubleValue(ref int value)
{
value = value * 2;
}
public static void Main()
{
int number = 5;
RefExample example = new RefExample();
Console.WriteLine("Before: " + number);
example.DoubleValue(ref number);
Console.WriteLine("After: " + number);
}
}
Output:
Before: 5
After: 10
✅ Key Points
- Pass by Reference: The method modifies the original variable.
- Requires Initialization: Variables passed with
refmust be initialized first. - Persistent Changes: Changes made inside the method reflect in the caller.
๐ Swap Example (Multiple Ref Parameters)
public void Swap(ref int x, ref int y)
{
int temp = x;
x = y;
y = temp;
}
public static void Main()
{
int a = 5, b = 10;
Swap(ref a, ref b);
Console.WriteLine($"a = {a}, b = {b}");
}
⚙️ Use Cases for ref
- Return multiple values from a method
- Improve performance for large objects
- Update values without returning a result object
๐ซ Limitations
- Must be initialized before use
- Can make code harder to read if overused
- Does not support method overloading based on ref
๐ ref vs out
| Feature | ref | out |
|---|---|---|
| Initialization Required Before Passing? | ✅ Yes | ❌ No |
| Must Be Assigned in the Method? | ❌ No | ✅ Yes |
| Usage | Read/Write | Write Only (initially) |
๐งช Example with out
public void TryParse(string input, out int result)
{
if (!int.TryParse(input, out result))
{
result = -1;
}
}
๐ Conclusion
ref in .NET Core is a powerful feature that allows efficient memory use and supports multi-value returns. Use it when you need to update input values directly, but don’t overuse it—clarity is key!
Comments
Post a Comment