Pass by reference in C #
Conclusion
Use ref
.
sample
class Program
{
static void Main(string[] args)
{
int a = 5;
//A copy of the variable of a is passed (passed by value)
PrmtvSample(a);
//Does not affect the original variable
Console.WriteLine(a);
//Pass the actual condition of a (pass by reference)
RefSample(ref a);
//Affects the original variable
Console.WriteLine(a);
public static void PrmtvSample(int a)
{
a *= 200;
Console.WriteLine(a);
}
public static void RefSample(ref int a)
{
a *= 100;
Console.WriteLine(a);
}
}
}
Output result
1000
5
500
500
Of course, if you do not specify anything, it is ** passed by value **, but when passing by reference in C #, just use ref
.
Also, ** initialization is required ** when passing with ref
.
I won’t explain it here, but if you use ʻunsafe`, you can also use operators related to pointers.
If you are interested in C # pointers, click here (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/pointer-related-operators)
Passing by reference affects the original object ~~ It affects the variable of the caller, but passing by value is where the value is copied and passed.
Strictly speaking, since it is a topic that tends to be controversial, is the expression ** passed by reference ** correct? (Because the formula also says “value passed by reference”)