What’s that keyword: ref

When you call a method and pass a value as an input parameter, you might do something with that parameter. For example you have an integer type variable called myNum, that is 10.

int myNum = 10;

You have a simple method like this:

static void WithoutRef(int _input)
        {
            _input = 30;
        }

This waits for an integer type input parameter called _input. You call this method with the variable myNum:

WithoutRef(myNum);

As you leave the method, your original variable myNum has still the same value of 10. So we passed the variable as value. Only its value has been passed and modified within the method. We created a copy of the variable in the memory and made the changes on the new copy.

What if you pass this variable as reference and not value? You should have this method then:

static void WithRef(ref int _input)
        {
            _input = 30;
        }

You should call this method this way with the variable myNum:

WithRef(ref myNum);

After returning from the method, your variable myNum has a new value of 30! So you didn’t change only the value but the entire memory reference too. Now you’re totally lost the value of 10 of the variable myNum. If it was a class level variable, now it has a new value across the whole class.