Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need to use out keyword while calling a method

Tags:

c#

.net

clr

When a method is defined with an out parameter, why do I have to specify the out keyword when calling it. Its already there in the method definition, and the runtime should know that any parameter passed will be an out parameter.

It would make sense if the compiler will accept the argument with or without out keyword, with different semantic, but if you MUST add the keyword to make the code compile, whats the use? Shouldn't the compiler handle it automatically?

Same for ref

like image 606
Midhat Avatar asked Jun 18 '10 06:06

Midhat


People also ask

Why do we need the out keyword?

The out is a keyword in C# which is used for the passing the arguments to methods as a reference type. It is generally used when a method returns multiple values. The out parameter does not pass the property. The ref is a keyword in C# which is used for the passing the arguments by a reference.

Why we use out parameter in C#?

The out parameter in C# is used to pass arguments to methods by reference. It differs from the ref keyword in that it does not require parameter variables to be initialized before they are passed to a method. The out keyword must be explicitly declared in the method's definition​ as well as in the calling method.

What is the purpose of out and ref keyword in C#?

The out and the ref parameters are used to return values in the same variables, that you an argument of a method. These both parameters are very useful when your method needs to return more than one values.

Do you need to declare out variable before you use it C#?

In C# 6 and earlier, you must declare a variable in a separate statement before you pass it as an out argument. The following example declares a variable named number before it is passed to the Int32. TryParse method, which attempts to convert a string to a number.


2 Answers

It is really great for readability. Also it will help you to avoid unexpected behaviors. While calling method with out param you will definitely know that the value of passed variable can be changed.

like image 115
Incognito Avatar answered Sep 20 '22 10:09

Incognito


This requirement is not there for the compiler's sake. f (x, out y) instantly informs whoever is reading the code that y is going to be overwritten after f returns, without the need of looking up the definition of f, saving them mental CPU cycles.

like image 23
Anton Tykhyy Avatar answered Sep 20 '22 10:09

Anton Tykhyy