Return with 2 Values C # [duplicate]

3

I want to give return of two values in C #. My code is so currently, just returning imagePath , but I want to return imagePath and normalPath at the same time.

string imagePath = "~/Images/QrCode.jpg";
string normalPath = "~/Images/TESTE.jpg";
return imagePath;
    
asked by anonymous 18.04.2018 / 18:36

2 answers

11

It is possible, if you are using C # 7 or higher, using Tuples .

public (string, string) OseuMetodo()
{    
    string imagePath = "~/Images/QrCode.jpg";
    string normalPath = "~/Images/TESTE.jpg";
    return (imagePath, normalPath);
}

Call the method this way:

var (imagePath, normalPath) = OseuMetodo();

The above code not only declares the variables imagePath and normalPath but assigns them the returned values.

    
18.04.2018 / 19:19
3

There are some possible solutions to this problem, but in none you return two values.

1. You can transform the method into void and receive two variables to "return" what you need:

public void CarregarPath (ref string imagePath, ref string normalPath){
    imagePath = "~/Images/QrCode.jpg";
    normalPath = "~/Images/TESTE.jpg";
}

2. You can return an array with these two faces:

public string[] CarregarPath (){
    string[] retorno = new string[2];

    retorno[imagePath] = "~/Images/QrCode.jpg";
    retorno[normalPath] = "~/Images/TESTE.jpg";

    return retorno;
}

3. If you have more attributes for this guy, you can create a class and return it:

public class PathCompleto {
    string ImagePath { get; set; }
    string NormalPath { get; set; }
}

public PathCompleto  CarregarPath (){
    PathCompleto  retorno = new PathCompleto();

    retorno.ImagePath = "~/Images/QrCode.jpg";
    retorno.NormalPath = "~/Images/TESTE.jpg";

    return retorno;
}
    
18.04.2018 / 19:17