We have recently been asked for the correct use of the REF keyword, which we will illustrate here. In fact, to better understand the ref keyword, combining C + + code is easier. In addition, before starting our example, we need to explain a few things in advance:
There are two types of data in C #: A reference type (reference types) and a value type (values types). simple types (including int, long, double, etc.) and structs (structs) are value types, while other classes are reference types. A simple type replicates when the value is passed, and the reference type simply passes the reference, just like a pointer in C + +.
Note the difference between structs in C # and C + +. In C + +, structs and classes are essentially the same (except that default inheritance and default access are public rather private). In C #, structs and classes are very different. One of the biggest differences (which I personally think is also easy to overlook) may be that it is a value type, not a reference type.
The following code is an example of MSDN:
// cs_ref.cs
using System;
public class MyClass
{
public static void TestRef(ref char i)
{
// The value of i will be changed in the calling method
i = 'b';
}
public static void TestNoRef(char i)
{
// The value of i will be unchanged in the calling method
i = 'c';
}
// This method passes a variable as a ref parameter; the value of the
// variable is changed after control passes back to this method.
// The same variable is passed as a value parameter; the value of the
// variable is unchanged after control is passed back to this method.
public static void Main()
{
char i = 'a'; // variable must be initialized
TestRef(ref i); // the arg must be passed as ref
Console.WriteLine(i);
TestNoRef(i);
Console.WriteLine(i);
}
}
It is easy to see that the output is:
b
b
So if you make some new changes to this example, change the value type (here with char) to a reference type, what effect does the program run?
// ----------------------------------------
// MyClass definition
public class MyClass
{
public int Value;
}
// ----------------------------------------
// Tester methods
public static void TestRef(ref MyClass m)
{
m.Value = 10;
}
public static void TestNoRef(MyClass m)
{
m.Value = 20;
}
public static void TestCreateRef(ref MyClass m)
{
m = new MyClass();
m.Value = 100;
}
public static void TestCreateNoRef(MyClass m)
{
m = new MyClass();
m.Value = 200;
}
public static void Main()
{
MyClass m = new MyClass();
m.Value = 1;
TestRef(ref m);
Console.WriteLine(m.Value);
TestNoRef(m);
Console.WriteLine(m.Value);
TestCreateRef(ref m);
Console.WriteLine(m.Value);
TestCreateNoRef(m);
Console.WriteLine(m.Value);
}