Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

optional/null-able OUT parameter in C#

Tags:

I have a method that has several overrides. In one of the more expanded overrides, I want to return an OUT parameter but not in my simpler overrides. For example:

public bool IsPossible(string param1, int param2) public bool IsPossible(string param1, int param2, out bool param3) 

The way I am currently achieving this, is like so:

public bool IsPossible(string param1, int param2) {     bool temp;     return IsPossible(param1, param2, out temp); } 

Is there a better way to achieve this? Can I (or should I) use a null-able out parameter?

like image 611
Derek Hunziker Avatar asked Jun 30 '11 18:06

Derek Hunziker


People also ask

Can out parameter be optional?

When a method with an omitted optional parameter is called, a stack frame containing the values of all the parameters is created, and the missing value(s) are simply filled with the specified default values. However, an "out" parameter is a reference, not a value.

What is out _ in C#?

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.

What are out parameters 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.

Do you need to declare an out variable before use it?

Calling a method with an out argument 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.


1 Answers

That looks fine to me. A out cannot be optional for technical reasons (it needs to point to a valid instance).

like image 190
Lucero Avatar answered Sep 22 '22 02:09

Lucero