Ref in .NET Core

Understanding 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 ref must 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

Popular posts from this blog

Debouncing & Throttling in RxJS: Optimizing API Calls and User Interactions

Promises in Angular

Comprehensive Guide to C# and .NET Core OOP Concepts and Language Features