views:

62

answers:

3

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?

+5  A: 

No, don't use a ref unless you want to change what list the variable is referencing. If you want to just access the list, do it without ref.

If you make a parameter ref, you are saying that the caller should expect that the parameter they pass in could be assigned to another object. If you aren't doing that, then it's not conveying the correct information. You should assume that all C# developers understand that an object reference is being passed in.

Lou Franco
+2  A: 

You don't need ref in your scenario, nor will it help with readability.

ref is only used if you intend to change what the variable references to, not the contents of the object it references. Does that make sense?

Esteban Araya
+2  A: 

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
}
recursive