-2

If I have something like:

        static string characterName()
    {
        Console.Write("Name your character: ");
        string name = Console.ReadLine();
        Console.Write("Is this correct? (Y/N): ");
        string nameConfirm = Console.ReadLine();
        return nameConfirm;
    }

How can I change this so it outputs both nameConfirm and name. The nameConfirm goes into:

        static string stageOne(string nameConfirm)
    {
        while (nameConfirm != "Y")
            nameConfirm = Program.characterName();
        if (nameConfirm == "Y")
        {
            Console.WriteLine("Alright, lets continue.");
            nameConfirm = Console.ReadLine();
        }
        return nameConfirm;

That works fine but I want to be able to call upon the name later if its needed.

Xydis
  • 13
  • 5
  • 3
    one way is to make the return collection of `string` rather than `string`, like `string[]` or `List` or `IEnumerable` or `Dictionary` and so on... You could also return `Tuple` – Ian Apr 21 '16 at 14:49
  • 1
    you can return a string collection, or an object with multiple string properties, or a tuple, or use the `out` keyword and functionality... – user1666620 Apr 21 '16 at 14:49

2 Answers2

1

There are two ways you could do this that aren't too overkill, the first is to return a string array

static string[] characterName()
{
    Console.Write("Name your character: ");
    string name = Console.ReadLine();
    Console.Write("Is this correct? (Y/N): ");
    string nameConfirm = Console.ReadLine();
    return new string[]{ nameConfirm, name };
}

This object can then be used like so

string[] names = characterName();
string runStageOne = stageOne(names[0]);

The other way you can do this is to return the nameConfirm variable and use the name variable as a ref, so your method would change to

static string characterName(ref string name)
{
    Console.Write("Name your character: ");
    string name = Console.ReadLine();
    Console.Write("Is this correct? (Y/N): ");
    string nameConfirm = Console.ReadLine();
    return nameConfirm;
}

And would be called like

string name = "";
string nameConfirmed = characterName(ref name);

By using the ref keyword on your input parameter, it means that when the value of name is changed in the method, that change is reflected outside of it too

Alfie Goodacre
  • 2,753
  • 1
  • 13
  • 26
0

You could return a List, a string[], or define a class to represent the result of the method (ie with two string properties)...

Martin Milan
  • 6,346
  • 2
  • 32
  • 44