t_plusplus
t_plusplus

Reputation: 4209

Using out parameter in a function that has a return value

I have a function such as this one:

public string MyFunction(int a, out int b)
{
   var test = ""
   b = 6;
   return test;
}

and then on the receiving end:

int b = 0;
var testOutcome = MyFunction(3, b);

I wonder how to get the value of: b in this scenario?

something like:

var bOutcome = ....; 

Upvotes: 2

Views: 105

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460138

You get the out parameter from the method. Note that you also need to add the out keyword in the parameter signature of the method:

int b = 0;  // initialization is redundant
string  testOutcome = MyFunction(3, out b);
// b is initialized now

Although variables passed as out arguments do not have to be initialized before being passed, the called method is required to assign a value before the method returns.

Upvotes: 7

Steve
Steve

Reputation: 216293

As written above your code will not compile because when using a method that receive an out parameter then you should add the keyword out also in the calling line.

You should change your calling line to

// No need to initialize b
// It is mandatory to initialize an out parameter for the called function
int b; 
var testOutcome = MyFunction(3, out b);

then your could simply check the value of b

if (b == 6)

A very common example scenario on how to use an out parameter is the Int32.TryParse method

Upvotes: 2

Related Questions