C# ref keyword usage

后端 未结 7 1363
耶瑟儿~
耶瑟儿~ 2020-12-10 03:39

I understand (or at least I believe I do) what it means to pass an instance of a class to a method by ref versus not passing by ref. When or under

7条回答
  •  死守一世寂寞
    2020-12-10 04:32

    The ref keyword allows you to pass an argument by reference. For reference types this means that the actual reference to an object is passed (rather than a copy of that reference). For value types this means that a reference to the variable holding the value of that type is passed.

    This is used for methods that need to return more than one result but don't return a complex type to encapsulate those results. It allows you to pass a reference to a object into the method so that the method can modify that object.

    The important thing to remember is that reference types are not normally passed by reference, a copy of a reference is passed. This means that you are not working with the actual reference that was passed to you. When you use ref on a class instance you are passing the actual reference itself so all modifications to it (like setting it to null for example) will be applied to the original reference.

提交回复
热议问题