-5

In c++ passing a const reference is often used to save time copying. I know that c# has a ref keyword, but the accepted answer in How do I pass a const reference in C#? says that it still creates a copy of the passed variable, but modifies them both. How can I prevent that?

  • 2
    What you wrote is not correct. See here about the ref keyword: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref – wohlstad May 07 '22 at 13:33
  • You've "heard something", you can try making a short program to test that out to see if it's true. – gunr2171 May 07 '22 at 13:33

1 Answers1

0

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

ItzHex
  • 90
  • 9