Understand the keywords “ref” and “out” in C # – Programming, Pseudocode Example, C# Programming Example
C# Console

Understand the keywords “ref” and “out” in C #

Explanation in a synthetic way about the functioning of the keywords ref and out, exclusive to the C # language.

Before going further in this article, it is necessary to understand the difference between value types and reference types.

ref

To fully understand ref, we will directly take a piece of code that uses this keyword:

As you can see, the keyword must be used as an argument as well when declaring a method as during its call. ref will therefore allow us to pass the reference of the variable in order to directly modify its value without going through the creation of a copy. Indeed, when passing a value argument, it is a copy that we manipulate and not directly its value, unlike reference types. So our piece of code will return 20. The absence of the keyword would have returned to us 10.

out

The out keyword allows a method to return multiple results in addition to its return value. Indeed, thanks to the use of this key word, you will be able to declare variables without initializing them and affect them when they pass in the body of a method through its parameters. Be careful, the method containing a parameter out must necessarily affect the associated variable.

So, in this very simple example, we observe a value type (a) that does not need to be initialized by using the out keyword.

A concrete example of using this keyword is the TryParse method of the Int32 class. This method allows you to return two things:

  • To check if it is possible to convert a string to an int (the return parameter of the function returns this possibility or not by a Boolean type)
  • To be able, in the possible case of a conversion, to assign this string in an int passed in parameter with the keyword out.

 

Note that for the second test, notANumber takes the default value of an int if the conversion is impossible: ie zero.

 

1 Comment

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: