Initial value never used, and method parameters not updating when code ran

82 views Asked by At

I want these method parameters, restart and winner to update a field in main. however, it doesnt seem to work because it says the value is never used. But I'm using it, so I don't understand;

'''
static void Restart(bool restart, bool winner, string[,] nums, bool[,] trueIfX, bool[,] trueIfO)
    {
        Console.WriteLine("would you liked to start a new game? Y/N");
        string input = Console.ReadLine();
        bool correctInput = false;

        do
        {

            if (input == "Y")
            {
                correctInput = true;
                restart = false;
                winner = false;
                nums[0, 0] = "1"; nums[0, 1] = "2"; nums[0, 2] = "3";
                nums[1, 0] = "4"; nums[1, 1] = "5"; nums[1, 2] = "6";
                nums[2, 0] = "7"; nums[2, 1] = "8"; nums[2, 2] = "9";
'''
2

There are 2 answers

0
oleksa On

do you need to return restart and winner back to the method that had executed the Restart() ?

You can use the ref or out keywords to do it ref means to pass parameter by reference. This allows called function to update the parameter value for caller like

static void Restart(ref bool restart, ref bool winner)
{
restart = true;
}

static void Main()
{
var restartparam = false;
var winner = false;
Restart(ref restartparam, ref winner);
if (restartparam)
  RestartNow();
}

However having a lot of ref parameters can be weired. So you can create a class and use it to pass data into the method.

like

class RestartOptions
{
public bool restart;
public bool winner;
}

static void Restart(RestartOptions opt)
{
opt.winner = true;
}

static void Main()
{
var options = new RestartOptions();
Restart(options);
if (options.winner)
  DispenseJackpot();
}

this allows you to modify RestartOptions class members and keep method signatures intact.

0
KingOfArrows On

You are getting this warning/error because warning is never actually used for something. Once you pass it to another function, use it in an if statement, etc, the warning/error will go away.

Think of it like having a builder as your employee and you give the employee a hammer. Yes you gave your worker the thing it needs, but now they're standing around waiting for you to use them for something.