4

I have been working with my software using C# in visual studio. But i want to return multiple values in my method, How to return multiple values in a method in C#.... Is it possible??

Umar Uzman
  • 71
  • 1
  • 1
  • 6
  • 1
    You need to use tuple please see the above answer. – TAHA SULTAN TEMURI Jul 17 '18 at 06:15
  • 1
    For clarity of your code it's best if you create class for holding your data and return it. Otherwise you can use array for values of same type or tupples, if you don't care about type safety, then you can use array of objects, or anonymous objects. – CrudaLilium Jul 17 '18 at 06:22
  • @CrudaLilium AFAIK anonymous types are typed – Cleptus Jul 17 '18 at 06:44
  • @bradbury9 You can't define anonymous return type, to be able to compile you must specify return type as object or dynamic, hence losing type safety. – CrudaLilium Jul 17 '18 at 06:52
  • @CrudaLilium although when used locally they are type safe, in this specific case you are right – Cleptus Jul 17 '18 at 07:15

4 Answers4

6

You can use .NET 4.0+'s Tuple:

For example:

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

it's much easier now

For example:

public (int, int) GetMultipleValue()
{
    return (1,2);
}
Shalinda Silva
  • 143
  • 1
  • 7
2

Do you want to return values of a single type? In that case you can return an array of values. If you want to return different type of values you can create an object, struct or a tuple with specified parameters and then assign those values to these parameters. After you create an object you can return it from a method.

Example with an object:

public class DataContainer
{
    public string stringType { get; set; }
    public int intType { get; set; }
    public bool boolType {get; set}

    public DataContainer(string string_type, int int__type, bool bool_type)
    {
       stringType = string_type;
       intType = int__type;
       boolType = bool_type;
    }
}

Example with a struct:

public struct DataContainer
{  
    public stringstringType;  
    public int intType;  
    public bool boolType;  
}  

Example with a tuple:

var DataContainer= new Tuple<string, int, bool>(stringValue, intValue, boolValue);
Anže Mur
  • 1,545
  • 2
  • 18
  • 37
  • 3
    Try to avoid answering questions that are duplicated, the question linked in [Natalia's comment](https://stackoverflow.com/questions/748062/how-can-i-return-multiple-values-from-a-function-in-c) Does provide this example and many more already. – Cleptus Jul 17 '18 at 06:43
0

You could create a struct that has multiple variables inside of it.

See https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/struct .

0

Your options are returning a struct, a class, a (named?) tuple or alternatively you can use out parameters

WynDiesel
  • 1,104
  • 7
  • 38