When to pass ref keyword in

后端 未结 6 926
野性不改
野性不改 2020-12-06 11:45

I\'ve read the difference between passng and not passing ref in parameters, however, when would I want to use them?

For example, I had some logic in a method which c

6条回答
  •  执念已碎
    2020-12-06 12:25

    Conceptually, the difference is that a value type stores its value directly, whereas a reference type stores a reference to the value. Maybe you should re-read a bit about reference vs value types.

    Passing value types by reference--as demonstrated above--is useful, but ref is also useful for passing reference types. This allows called methods to modify the object to which the reference refers because the reference itself is being passed by reference. The following sample shows that when a reference type is passed as a ref parameter, the object itself can be changed.

       class RefRefExample
    {
        static void Method(ref string s)
        {
            s = "changed";
        }
        static void Main()
        {
            string str = "original";
            Method(ref str);
            // str is now "changed"
        }
    } 
    

    MSDN

提交回复
热议问题