C# From a Java Developer’s Perspective: Reference and Output Parameters

Reference and Output Parameters

See, I told you there would be more awesome stuff coming along! Now let’s talk about a couple features in C#, reference parameters and output parameters.

Reference and output parameters both allow us to pass a value as a parameter by reference. To understand this, one must first understand passing by reference vs. passing by value. When a variable is passed by reference as a parameter, anything that happens to it in the method will be reflected when the method is called. Passing by value is the opposite; when the variable is passed, it’s only really a copy of the variable’s value, so the original isn’t affected.

Now that we’ve gotten that part down,  it time to discuss reference and output parameters.  Again, they’re both passed by reference, but reference variables must be initialized before being passed as a parameter whereas output variables mustn’t be.

When intending to pass in a value as a reference parameter, you simply have to use the keyword ref. Similarly, to do so for an output parameter, simply use the keyword out. Use cases for the two are below:

Reference parameter:

This quick code snippet shows two variables being assigned values of “1” and “2” respectively before being passed into the RefMethod function with the ref keyword and manipulated. If I were to run this program, I’d see that “val1” would be 45 and “val2” would be 49.

 

Output Parameter:

As you can see, output parameters don’t have to be initialized with a value before being passed. It is still very similar to ref in that it is still being passed by reference. If I were to run this program, I’d see the output being 40 and 41, respectively.

So What’s the Use?

Well, by default, if I were to not use the ref/out keywords and just pass a value in as a parameter, any changes made it that value would only be in the scope of that function. The actual value of the variable would not have changed as far as the rest of the program is concerned. By using ref/out, I’m actually referring directly to that variable, so it’ll be changed outside of the function’s scope. They become very useful, say, when one needs to return more than one value from a function!

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *