Ref and Out Reserved Keywords in Csharp – Part #2

Ref and Out Reserved Keywords in Csharp

Hi there,

Today, we’ll take a closer look at “out” and “ref” keywords in C#.

Let’s start with the basics of reference.

There are two types of passing a value in C#. The first type is pass by value, and it’s used with primitive types, such as ints, doubles, etc. In this case, when you pass an argument, it’s copied and all modifications are done on the copy, not the original variable as shown in the code below.

ref and out csharp keywords

Figure 1: Pass by value example output

The second type is pass by reference, and it’s used on objects. In this case, by modifying the parameter in the method, you’re changing the values that were passed in the method call. 

 

Using out and ref

Using “out” and “ref” keywords will change the original variables that you passed in the parameters. It works like pass by reference on all the variable types (not on properties though). To use either one, you need to specify the keyword in the method definition and also when calling the method. This way the programmer knows that the variable might change.

There’s a slight difference between them.

Using ref

To use the “ref” keyword, you need to declare the variables that will be passed in the parameters and assign the initial values to them. This is because C# enforces the rule that a variable, in order to be accessed (read), needs to be initialized.

The example shows a usage of ref keyword.

Example of using the ref keyword

Figure 2: Example of using the ref keyword

Using out

The “out” keyword stands for output. This means that the variable won’t be read in the method, and therefore it doesn’t have to have a value assigned upfront. The declaration is enough in this case because the method cannot read the variable and must assign a value to it before ending its execution.

 

The example below shows the use of both ref and out keywords. 

Example of using the out and ref keywords

Figure 3: Example of using the out and ref keywords

What else to know

  • they are useful when you want to return multiple values
  • they cannot be used for properties
  • they cannot be used with async methods

 


You can find more information about “out” here, and about “ref” here, and probably in any book about C# that talks about that.