TheLethalCoder
TheLethalCoder

Reputation: 6744

Inline the out parameter in a method call

When writing code I sometimes find it useful to return a bool value of successful and an out parameter of a code if needed. Or even using the TryParse functions and their respective out parameters.

A recent example of this was the following method signature:

private State GetTheStateOfClass1(Class1 o, out double confidence)

Here I have a method that finds the state of a Class1 object and its corresponding confidence that the object does have that state.

This method is used when creating a new instance of Class2 like so:

double confidence;
Class2 c2 = new Class2(GetTheStateOfClass1(o, out confidence), confidence, ...);

Is there a way that I can use an inlined out parameter like so:

Class2 c2 = new Class2(GetTheStateOfClass1(o, out double confidence), confidence, ...);

Upvotes: 2

Views: 1386

Answers (2)

dimanhog
dimanhog

Reputation: 21

This is possible as of C# 7.0:

Class2 c2 = new Class2(GetTheStateOfClass1(o, out double confidence), confidence, ...);

Upvotes: 1

Codor
Codor

Reputation: 17605

To my understanding, this is impossible; the out parameter is required to be an actual variable in the caller's scope. That being said, a workaround would be to create an overload that does not use the out parameter as follows.

private State GetTheStateOfClass1(Class1 o)
{
    double confidence;
    return GetTheStateOfClass1(Class1 o, out confidence);
}

Upvotes: 1

Related Questions