Hagwill Hagwill - 11 months ago 77
C# Question

C# How do I use a variable outside of a loop that changes from string to int inside the loop?

The code:

string[] numbers = new string[2];
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = Console.ReadLine();
if (int.TryParse(numbers[i], out int numberTry) && i == 0)
Console.WriteLine("That would be a number yes.");

else if (int.TryParse(numbers[i], out numberTry))
Console.WriteLine("Lovely work! That is indeed two numbers!");

else
{
Console.Clear();
Console.WriteLine("That's not a number. I am dissapointed.");
Console.ReadKey();
Environment.Exit(0);
}
}


My problem here is that I can't use numbers[] outside of the loop as an int because it chancges from a string to an int inside of the loop. I need to be able to send it with a method as an int to perform a operation on numbers[0] and numbers[1].
Thanks in advance!

Answer Source

Could you try this. It should work.

    int[] numbers = new int[2];
    for (int i = 0; i < numbers.Length; i++)
    {
        var number = Console.ReadLine();
        if (int.TryParse(number, out int numberTry) && i == 0)
        {
            Console.WriteLine("That would be a number yes.");
            numbers[i] = numberTry;
        }
        else if (int.TryParse(number, out numberTry))
        {
            Console.WriteLine("Lovely work! That is indeed two numbers!");
            numbers[i] = numberTry;
        }
        else
        {
            Console.Clear();
            Console.WriteLine("That's not a number. I am dissapointed.");
            Console.ReadKey();
            Environment.Exit(0);
        }
    }

    Console.ReadKey();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download