Suppose you have a method, say f, accepts a referenced typed parameter, say a.
The referenced type has a value-typed field, say b.
What if the b changes inside f? Will b changes as well after f for a?
The following code has been used to test the result via .NET Core CLI 2.0.0
using static System.Console;
namespace vf
{
class Program
{
static void Main(string[] args)
{
ReferenceType a = new ReferenceType();
WriteLine($"Initial value of a.b: {a.b}");
f(a);
WriteLine($"After f, value of a.b: {a.b}");
}
private static void f(ReferenceType a){
a.b++;
}
}
public struct ReferenceType{
public int b;
}
}
Curious to find that the value-typed field of a reference-typed instance as an argument passed to a method, which takes usual parameters.does not change after the method is called. That is to say, b does not change to 1 as expected.
Then we look back at the definition of value type and reference type again. Only to find a fact that has been negalected ...
A struct type (including user defined struct) is a value type.
Therefore, if we change the definition from struct toclass, everything will work as expected in the assumption ahead.
To achieve the assumption above still with struct definition, we can use
ref to introduce the parameter as a reference.