Walkthrough

What's the difference between

public function Foo(ref Bar bar)
{
   bar.Prop = 1;
}

public function Foo(Bar bar)
{
   bar.Prop = 1;
}

in essence, what is the meaning of "ref". is not always an object by reference?

+3
source share
2 answers

The fact is that you never pass an object. You pass a link - and the argument itself can be passed by reference or value. They behave differently if you yourself change the value of the parameter, for example. by setting it to nullor to another link. With refthis change affects the caller variable; without refit, there was only a copy of the passed value, so the caller does not see the changes in its variable.

See my article on passing arguments for more details .

+10

. :

public function Foo(ref Bar bar)
{
   bar = new Bar();
}

public function Foo(Bar bar)
{
    bar = new Bar();
}

. , . - .

+9

Source: https://habr.com/ru/post/1706108/


All Articles