Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to explicitly discard an out argument?

Tags:

c#

out

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?

like image 581
Andrew Ducker Avatar asked Jan 20 '09 17:01

Andrew Ducker


People also ask

What is the best way of declaring an out parameter that is never going to be used?

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.

What is discard in C sharp?

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.


1 Answers

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/

like image 142
Nolonar Avatar answered Sep 18 '22 21:09

Nolonar