I'm having trouble understanding what exactly the ref
keyword in C# does.
In my C++ code I am creating a string variable along with a pointer and reference variable pointing to it. I'm passing it to either a Delete or Change function, and as expected all 3 variables are being modified.
However, with C#, I'm creating variable x
and initialising it with string data. I'm creating a variable y
which should under the hood be a reference to x
. I'm then passing x
into the Change
or Delete
method with a ref
keyword, causing the variable inside the method, as well as x
to be modified. However, y
is not modified, even though it should be a reference to x
, just like in C++. This is not just an issue with strings either, as I have tried the above test with a C# object, and had the same results.
Does this mean y
copied x
by value when I executed var y = x
?
C++
#include <iostream>
using namespace std;
void Delete(string &variable)
{
variable = "";
}
void Change(string &variable)
{
variable = "changed data";
}
void main()
{
string x = "data";
string *y = &x;
string &z = x;
Delete(x);
}
c#
namespace ConsoleApplication1
{
public class Program
{
public static void Main(string[] args)
{
var x = "data";
var y = x;
Change(ref x);
}
public static void Delete(ref string variable)
{
variable = null;
}
public static void Change(ref string variable)
{
variable = "changed";
}
}
}