When is using the C# ref keyword ever a good idea?

后端 未结 10 965
情歌与酒
情歌与酒 2020-11-29 06:05

The more I see ref used in production code, the more misuse I encounter and the more pain it causes me. I have come to hate this keyword, because from a framework-building s

10条回答
  •  误落风尘
    2020-11-29 06:36

    The Framework Design Guidelines (a book by Krzysztof Cwalina and Brad Abrams) recommend to avoid both ref and out parameters.

    AVOID using out or ref parameters.

    Using out or ref parameters requires experience with pointers, understanding how value types and reference types differ, and handling methods with multiple return values. Also, the difference between out and ref parameters is not widely understood. Framework architects designing for a general audience should not expect users to master working with out or ref parameters.

    The Framework Design Guidelines cite the canonical Swap method as a valid exception:

    void Swap(ref T obj1, ref T obj2)
    {
        T temp = obj1;
        obj1 = obj2;
        obj2 = temp;
    }
    

    but at the same time a comment remarks

    Swap always comes up in these discussions, but I have not written code that actually needed a swap method since college. Unless you've got a very good reason, avoid out and ref altogether.

提交回复
热议问题