Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return multiple values to a method caller

Tags:

c#

return

I read the C++ version of this question but didn't really understand it.

Can someone please explain clearly if it can be done in C#, and how?

like image 525
Ash Avatar asked Apr 14 '09 15:04

Ash


People also ask

Can you return multiple values in a method?

You can return only one value in Java. If needed you can return multiple values using array or an object.

How many values a method can return to its caller?

Answer: The value-returning function returns only one value by using the return statement.

How do I return multiple items in Java?

You can return an object of a Class in Java. If you are returning more than 1 value that are related, then it makes sense to encapsulate them into a class and then return an object of that class. If you want to return unrelated values, then you can use Java's built-in container classes like Map, List, Set etc.


1 Answers

In C# 7 and above, see this answer.

In previous versions, you can use .NET 4.0+'s Tuple:

For Example:

public Tuple<int, int> GetMultipleValue() {      return Tuple.Create(1,2); } 

Tuples with two values have Item1 and Item2 as properties.

like image 98
Hadas Avatar answered Sep 19 '22 17:09

Hadas