Richard Scholey
Richard Scholey

Reputation: 83

Is there a way to ignore an out parameter from a method call when it's not needed?

Here is the code that I have:

    private int _utcNow;
    private string _yymmdd;

    public void AddScreenHistory(int Seconds)
    {
        Helper.GetDates(out _yymmdd, out _utcNow);
        
        // _yymmdd is used
        // _utcNow is not used
    }

I have declared _utcNow as a private to avoid a compiler error, but is there a way that I can avoid declaring it at all?

Upvotes: 1

Views: 1336

Answers (2)

pinkfloydx33
pinkfloydx33

Reputation: 12789

Prior to C#7, you would need a variable (likely local) to dump the result in:

int discard;
Helper.GetDates(out _yymmdd, out discard);

If you are using C# 7.0 or newer you can make use of the "Discards" feature.

Helper.GetDates(out _yymmdd, out _);

You can even discard more than one parameter at a time:

Helper.GetDates(out _, out _); // valid! 

Note the "unnamed" placeholder _. Trying to reference it is a compiler error:

Helper.GetDates(out _yymmdd, out _);
Console.WriteLine(_); // error! See below 

This can also be used to indicate that you are purposely discarding the result of a method call:

_ = SomeMethodThatReturnsValue();

Be careful though, there is some trickery in these two forms if you combine with var:

// this is a discard
Helper.GetDates(out _yymmdd, out var _);
Console.WriteLine(_); // error!

// this is not
var _ = SomeMethodThatReturnsValue();
Console.WriteLine(_); // no error!

The first case results in an error due to the discard but the second case declares and assigns to a variable named _. Even more interesting is the following which combines both syntaxes but only declares one variable (the output is "True"):

var _ = int.TryParse("1",out var _);
Console.WriteLine(_);

If you already happened to have a variable named _ in scope then the syntax no longer becomes a discard.

int _;
Helper.GetDates(out _yymmdd, out _); 
Console.WriteLine(_); // valid and will hold the out parameter's value 

As mentioned in the comments, if you rewrote GetDates such that it returned a tuple, you could discard the portion you don't want:

public static (string, int) GetDates()
{
   return ("210408", 12345);
} 

// usage, tuple discard
(_yymmdd, _) = Helper.GetDates();

Upvotes: 2

Enigmativity
Enigmativity

Reputation: 117144

Yes, just do this:

Helper.GetDates(out _yymmdd, out _);

Upvotes: 2

Related Questions