How to explicitly discard an out argument?

Andrew Ducker picture Andrew Ducker · Jan 20, 2009 · Viewed 33.2k times · Source

I'm making a call:

myResult = MakeMyCall(inputParams, out messages);

but I don't actually care about the messages. If it was an input parameter I didn't care about I'd just pass in a null. If it was the return I didn't care about I'd just leave it off.

Is there a way to do something similar with an out, or do I need to declare a variable that I will then ignore?

Answer

Nolonar picture Nolonar · Nov 30, 2016

Starting with C# 7.0, it is possible to avoid predeclaring out parameters as well as ignoring them.

public void PrintCoordinates(Point p)
{
    p.GetCoordinates(out int x, out int y);
    WriteLine($"({x}, {y})");
}

public void PrintXCoordinate(Point p)
{
    p.GetCoordinates(out int x, out _); // I only care about x
    WriteLine($"{x}");
}

Source: https://blogs.msdn.microsoft.com/dotnet/2017/03/09/new-features-in-c-7-0/