ALLINSIGHT

Home of the AlmostImplementedException

How to use Method Parameters ref, out, params

Today I want to show you, how we can use method parameters to solve specific problems.
At first, we’ll look at ref and out. Normaly a parameter is used to give a value into a function or method. But sometimes we need a different behavior.
If we want to return multiple values the out-keyword is our best friend. When you want to use out, you have to write the out-keyword ahead of the parameter and as well in the method-call.
This little example show us how to do it.

As you can see, i declared an Example-method with 2 out parameters. Both parameters are filled with a value in the method and the Main-Method write them to the console. It is also possible to assign null to a parameter. This way you can a out-parameter as optional. We can achieve the same result with the ref-keyword.

But ref can do more for us. If we want to deliver multiple values to a method that can be changed and returned, ref is the keyword.
Ref is used like out, but you have to initialize every variable you use with ref.

It is possible to overload a method with ref or out for a parameter but not both.

Now something completly different, the params-keyword.
Sometimes we need a method with n-parameters and we don’t know yet how many. For this we can use an array, but they more complicated to use when calling the method.
Lets have a look at an example:

As you can see, a method using params is very easy to call. You can use params only on one parameter and it have to be the last one.

Share :

, , ,

Comments are currently closed.