C# Pointers in a Method's arguments?

后端 未结 5 2048
一个人的身影
一个人的身影 2021-01-11 22:24

I wish to directly modify a variable\'s value outside of a method from inside it.
Pointers are the way, correct?

How?

5条回答
  •  滥情空心
    2021-01-11 22:51

    You can use the method parameter keyword ref:

    void modifyFoo(ref int foo)
    {
        foo = 42;
    }
    

    Call like this:

    int myFoo = 0;
    modifyFoo(ref myFoo);
    Console.WriteLine(myFoo);
    

    Result:

    42
    

    From the documentation:

    The ref method parameter keyword on a method parameter causes a method to refer to the same variable that was passed into the method. Any changes made to the parameter in the method will be reflected in that variable when control passes back to the calling method.

    To use a ref parameter, the argument must explicitly be passed to the method as a ref argument. The value of a ref argument will be passed to the ref parameter.

提交回复
热议问题