Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return multiple values in a method in C#.... Is it possible? [duplicate]

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??

like image 914
Umar Uzman Avatar asked Mar 06 '23 19:03

Umar Uzman


2 Answers

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);
}
like image 103
Shalinda Silva Avatar answered Mar 13 '23 00:03

Shalinda Silva


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);
like image 26
Anže Mur Avatar answered Mar 13 '23 00:03

Anže Mur