Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does c#'s ref copy and how to prevent it?

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading