Search code examples
variablescall

I can't figure out how to call a variable from another method


I am am trying to call a variable in another method to my array. var Com = the difficulty for the game. But the method below I'm trying to call the var Com, for: var c = Com.GetChoice();

Not sure why I can not figure out how to call it.

public object SetDiff()
        {
            Console.WriteLine("Enter difficulty #: (1 = Easy, 2 = Normal, 3 = Impossible)");
            var diff = Console.ReadLine();
            int mode;
            int.TryParse(diff, out mode);

            if (mode == 1)
            {
                Console.Clear();
                var Com = new Easy();
                return Com;
            }
            if (mode == 2)
            {
                Console.Clear();
                var Com = new Medium();
                return Com;
            }
            if (mode == 3)
            {
                Console.Clear();
                var Com = new Hard();
                return Com;
            }
            else
            {
                Console.WriteLine("That is not a valid input.");
                return SetDiff();
            }
        } // Apparently you can't set variables in a switch.

        public int[] FaceOff(int num)
        {
            int PlayerWin = 0;
            int ComWin = 0;
            int Tie = num + 1;
            // TODO : Get rid of TIES! 
            for (int i = 0; i < num; i++)
            {
                var p = p1.GetChoice();
                var c = Com.GetChoice();

Solution

  • You have many different options:

    Pass as parameter

     public int[] FaceOff(int num, int Com){...}
    

    make a "global" variable

    private int Com;
    

    I would also recommend you to learn OOP (Object Orientated Programming) basics.