Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to omit out parameter? [duplicate]

Let's assume I have a function with out parameter, however I do not need its value. Is there a way to pass no actual parameter if given result will be thrown away anyway?

EDIT:

Although the question has been voted to be dupe of Optional Output Parameters it only is if you look from the method creator's perspective. If you're the user of the method, you're interested not in making the parameter optional, just not using it without declaring the variable. And while this is not possible, with C# 7.0 it is possible to declare it in method call. So instead of:

int unusedValue; TryGetValue("key", out unusedValue); 

you get:

TryGetValue("key", out int unusedValue); 

or even:

TryGetValue("key", out _); 

This should be added as an answer, but:

  • I can't do this for this question, because it was marked as a dupe;
  • the question this question is seemed as a dupe of actually asks for a different thing.
like image 728
konrad.kruczynski Avatar asked Jan 19 '11 20:01

konrad.kruczynski


1 Answers

You cannot do this, but there's no rule saying that you have to use the value that comes back. You can simply pass a temporary variable that you never use again.

C# 4.0 allows optional parameters, but out parameters can't be optional.

EDIT: BTW, you can also overload the method:

int DoStuff() {     int temp;     return DoStuff(out temp); }  int DoStuff(out outParam) {     //... } 
like image 176
Justin Morgan Avatar answered Sep 24 '22 02:09

Justin Morgan