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

后端 未结 10 892
情歌与酒
情歌与酒 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:28

    Maybe when you have a struct (which is a value type):

    struct Foo
    {
        int i;
    
        public void Test()
        {
            i++;
        }
    }
    
    static void update(ref Foo foo)
    {
        foo.Test();
    }
    

    and

    Foo b = new Foo();
    update(ref b);
    

    Here you would to use two-parameters with out like:

    static void update(Foo foo, out Foo outFoo) //Yes I know you could return one foo instead of a out but look below
    {
        foo.Test();
    
        outFoo = foo;
    }
    

    imaging the method having more than one Foo then you would get twice the parameters with out versus ref. An alternative is to return a N-tuple. I don't have a real-world example on when to use this stuff.

    Add on: Different .TryParse methods could also have avoided out if they returned Nullable instead which essentially is a tuple of boolean * T.

提交回复
热议问题