[Solved] C# – How to get variables from a different method?


You can make them instance variables of the class containing the two methods. This way, they are accessible to all the methods of the class, and it’s value is preserved between the calls to those methods.

class ContainingClass
{
    int randomNumber;
    int randomNumber2;

    public void generateNumbers()
    {
        Random rand = new Random();
        randomNumber = rand.Next(1, 11);
        randomNumber2 = rand.Next(1, 11);
        Console.WriteLine("Number1: " + randomNumber);
        Console.WriteLine("Number2: " + randomNumber2);
    }

    public int findSum()
    {
        return randomNumber + randomNumber2; //gets sum from the method generateNumbers()
    }
}

1

solved C# – How to get variables from a different method?