Return two strings with a function in C#

Some options:

  • Use an out parameter:

    public string PlayerCards(out string x)
    

    Return one value, and set the out parameter (x in this case) to another value; the calling code will need to specify an argument with out as well, and after the call has completed, the caller will be able to see the value set in the method.

    (It's not clear why you're accepting parameters at all; you don't seem to really use them.)

  • Return a ValueTuple<string, string>, ideally using C# 7 tuples to provide element names

  • Return a Tuple<string, string>
  • Create a new type to store the two values together, assuming it's a meaningful combination. This is definitely a good choice if the values are related in a way which you'll use elsewhere. For example, instead of having a method returning one string for the suit of a card and one for the value, you'd create a PlayingCard type.
  • Refactor your code into two method calls, each of which return a single value

It's not at all clear what your code is trying to do - the name of the method isn't clear and you don't use the parameters. When you've clarified what the method is trying to achieve - to yourself as much as to us - the answer may well become more obvious.

I'd also encourage you to use local variables where appropriate - I suspect generatedCard should be a local variable instead of the (presumably) instance variable it currently is.


You can return tuple: Tuple<string, string>

Tuple<string, string> t = new Tuple<string, string>(player1C1,player1C2);

return t;

One of the several possible options:

Create a struct like this:

struct Players
{
  public string Player1;
  public string Player2;
}

Then use it in your function like this:

public Players PlayerCards()
    {   
        Players p1;
        generatedCard = randomCard.Next(1, 52);
        p1.Player1 = generatedCard.ToString();
        p1.Player2 =  p1.Player1 + ".png";            
        return p1;
    }

Tags:

C#

String

Return