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?
While you can't actually make the out parameter optional, you could simply create an overload for the function without the out parameter, which would then take away the need to create a temporary variable. This answer is more functional. No need to modify later on if you want to use it or not use it anymore.
Starting with C# 7.0, C# supports discards, which are placeholder variables that are intentionally unused in application code. Discards are equivalent to unassigned variables; they don't have a value.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With