Return with 2 C#Values

Asked

Viewed 1,011 times

3

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

string imagePath = "~/Images/QrCode.jpg";
string normalPath = "~/Images/TESTE.jpg";
return imagePath;

2 answers

11


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 variables imagePath and normalPath how I assigned the respective returned values.

3

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

1.You can turn 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.Can return one array with these two guys:

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 to him:

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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.