C# language: ref, out i params modifiers parameters

I do not know if you were wondering, but the variables sent as parameters to the method are copies because the method will not affect the sent variable and you may wonder if you can do so that the variable can be changed in the method to which we sent it, the modifiers ref and out are serve to that about which will be discuss today.

Ref Modifier

I will use a trivial example to make it easy to understand, first a standard example of sending a variable as an argument to the method:

It is known that the console will first show the number changed in the ChangeSendArgument method, that is 13, and then the number 12 so variable that we sent as an argument, ie the variable “a” has not changed, and we want the variable “a” sent as an argument, if will change in the method to which we sent this variable to change also in the place where we sent it. How to do it, very simply, just add two keywords:

I think that this example with comments is clearly enough to explain this, increasing the argument in the ChangeSendArgument method by one also changes the variable “a” by one, that is, you can say that they cooperate with each other 🙂

Out Modifier

The modifier out differs from the ref that:

1. It do not need to have a value assigned before it is passed to a function.

2. Must have a value assigned before leaving the function.

Below is an example:

As in the points above, the difference is that in the beginning there is no value.

Params Modifier

The params modifier means that the method can take any number of arguments. Below is an example:

This content also you can find on my steemit blog: https://steemit.com/programming/@slawas/c-language-ref-out-i-params-modifiers-parameters

And on medium: https://medium.com/@sawomirkowalski/c-language-ref-out-i-params-modifiers-parameters-a17278461bf6

If that post was useful for you share it with your friends :)

Post a comment

Notify about