0

I got 2 subroutines which make it so that they ask two different players for a name, but when I call on it in the main, it says a argument1 must be passed with a 'ref' keyword, but am I not doing that already?

static string GetPlayer1(ref string name1)
{
    Console.WriteLine("PlayerX enter your name:");
    name1 = Console.ReadLine();
    return name1;
}

static string GetPlayer2(ref string name2)
{
    Console.WriteLine("PlayerO enter your name:");
    name2 = Console.ReadLine();
    return name2;
}

static void Main(string[] args)
{
    string name1 = GetPlayer1(name1);
    string name2 = GetPlayer2(name2); 
...
Nurjan
  • 5,889
  • 5
  • 34
  • 54
Pavvel
  • 23
  • 2
  • 7

3 Answers3

4

Here the ref in the method parameters is unneeded, in fact you don't even need parameters at all. Change it to this:

static string GetPlayer1()
{
    Console.WriteLine("PlayerX enter your name:");
    return Console.ReadLine();
}

static string GetPlayer2()
{
    Console.WriteLine("PlayerO enter your name:");
    return Console.ReadLine();
}

static void Main(string[] args)
{
    string name1 = GetPlayer1();
    string name2 = GetPlayer2();
}


However if it was your intention to use ref (as an example or an exercise), then this would be how to do it. The methods now do not have a return type (void instead of string) because the texts are returned by means of assignment to the ref parameters.

static void GetPlayer1(ref string name1)
{
    Console.WriteLine("PlayerX enter your name:");
    name1 = Console.ReadLine();
}

static void GetPlayer2(ref string name2)
{
    Console.WriteLine("PlayerO enter your name:");
    name2 = Console.ReadLine();
}

static void Main(string[] args)
{
    string name1;
    string name2;
    GetPlayer1(ref name1);  // "ref" must now be specified, simply because
    GetPlayer2(ref name2);  // both methods also specify it.
}


For more about ref (e.g. when or how to use it), see these questions:
- Example of practical of "ref" use
- Why use the 'ref' keyword when passing an object?

Community
  • 1
  • 1
Peter B
  • 22,460
  • 5
  • 32
  • 69
0

Actually, you are not doing that:

    string name1 = GetPlayer1(ref name1);
    string name2 = GetPlayer2(ref name2); 

What you did is to add the ref keyword to your method definition (creating a ref parameter). You have to use it also in your method call (creating a ref argument).

In your current case though there is no need to pass the arguments by ref. You are setting them with the return value of your GetNamemethod.

Sefe
  • 13,731
  • 5
  • 42
  • 55
0

If you define a method with a ref parameter, you need to call that method with the parameter as reference:

static void Main(string[] args)
{
    string name1 = GetPlayer1(ref name1);
    string name2 = GetPlayer2(ref name2);
}

And just for completeness, as the other answers already tell you: I don't see the necessity for reference-calling here, you can accomplish your goals without it.

Michael Beck
  • 120
  • 1
  • 3
  • 11