Search code examples
c#ref

Does ref copy the variable?


In C++ it's possible to pass object to a function by value and by reference.

class MyClass {
    // ...
}

void foo(MyClass by_value) {
    // ...
}

void bar(MyClass& by_reference) {
    // ...
}

Passing objects by reference in C++ is usually better as it prevents object's copy constructor from being called.

C# has a ref keyword, which seems to be similar to c++'s reference.

But How do I pass a const reference in C#? says that the reference is copied. Does that mean that the object itself is also copied?


Solution

  • The ref keyword is used to pass an argument by reference, not value. The ref keyword makes the formal parameter alias for the argument, which must be a variable. In other words, any operation on the parameter is made on the argument.

    For example:

    void Method(ref int refArgument)
    {
        refArgument = refArgument + 44;
    }
    
    int number = 1;
    Method(ref number);
    Console.WriteLine(number);
    // Output: 45
    

    So to answer your question, no the ref keyword does not "copy" the variable.

    You can read more about the ref keyword here: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref