Search code examples
c#methodsparametersref

What exactly is parameter containing with ref modifier?


I want to ask something about ref modifier.

What I know and understand: With method that use ref modifier, there will be no copy of data as with passing by value, but parameter will have directly access to argument value. Basically said, all you done in method’s scope will act same as if you would done it with argument (passed variable) in caller’s scope.

and I want to ask what is exactly stored in parameter with ref modifier: When I pass argument to method with ref modifier, will parameter contain reference to value of argument? or is it something else?

Thank you for your answers


Solution

  • When you have a parameter with the ref attribute, it passes the argument by reference and not value. That means a new copy of the variable is not being made, rather a pointer to the original is being used within your function.

    public void Foo()
        {
            var x = 0;
            Bar(x); // x still equals 0
            Bar(ref x); // x now equals 1
        }
    
        public void Bar(ref int x)
        {
            x = 1;
        }
    
        public void Bar(int x)
        {
            x = 1;
        }