c# - should I use "ref" to pass a collection (e.g. List) by reference to a method?

Greg picture Greg · Aug 13, 2010 · Viewed 36.5k times · Source

Should I use "ref" to pass a list variable by reference to a method?

Is the answer that "ref" is not needed (as the list would be a reference variable), however for ease in readability put the "ref" in?

Answer

recursive picture recursive · Aug 13, 2010

A dictionary is a reference type, so it is not possible to pass by value, although references to a dictionary are values. Let me try to clear this up:

void Method1(Dictionary<string, string> dict) {
    dict["a"] = "b";
    dict = new Dictionary<string, string>();
}

void Method2(ref Dictionary<string, string> dict) {
    dict["e"] = "f";
    dict = new Dictionary<string, string>();
}

public void Main() {
    var myDict = new Dictionary<string, string>();
    myDict["c"] = "d";

    Method1(myDict);
    Console.Write(myDict["a"]); // b
    Console.Write(myDict["c"]); // d

    Method2(ref myDict); // replaced with new blank dictionary
    Console.Write(myDict["a"]); // key runtime error
    Console.Write(myDict["e"]); // key runtime error
}