How do you pass by reference in c#?
-
hi guys! I'm a newbie to c# Method signature: public static string Translate(string translationCode, string culture, ref Dictionary> input) I want to pass a dictionary by reference and not the entire object. Is it correct to use 'ref' in the argument? Then how do I insert the dictionary when calling the method? thanks
-
hi guys! I'm a newbie to c# Method signature: public static string Translate(string translationCode, string culture, ref Dictionary> input) I want to pass a dictionary by reference and not the entire object. Is it correct to use 'ref' in the argument? Then how do I insert the dictionary when calling the method? thanks
Reference types (objects) are never copied when you use them in a call. It's always the reference to the object that is sent to the method. If you use the ref keyword with a reference type, you will be sending a reference to the reference. Parameters are always sent by value unless you specify the ref keyword. For reference types that means that the value of the referecne is passed to the method. Example:
void Test(string a, ref string b) {
a = "1";
b = "2";
Console.WriteLine("a: " + a);
Console.WriteLine("b: " + b);
}string x = "x";
string y = "y";
Console.WriteLine("x :" + x);
Console.WriteLine("y :" + y);
Test(x, ref y);
Console.WriteLine("x :" + x);
Console.WriteLine("y :" + y);The output will be:
x: x y: y a: 1 b: 2 x: x y: 2
--- b { font-weight: normal; }