开发者

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

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开发者_JAVA技巧 for ease in readability put the "ref" in?


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
}


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.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜