0

i believe i solved the issue by by giving number1 and number2 a value of 0

im just starting out with coding and am trying to make a simple calculator. ive placed my string to int parse in a try block but now the rest of the app can not see the variables number1 or number2, how do i make it so that the rest of the app can see these variables?

int number1;
int number2;
try
{
    bool test1 = int.TryParse(input1, out number1);
    bool test2 = int.TryParse(input2, out number2);

    if (!test1)
    {
        throw new Exception("Convertion failed");
    }
}
catch (Exception ex) 
{
    Console.WriteLine("there was an error", ex.Message);
}

if (operation == add1 || operation == add2)
{
    int answer = number1 + number2;
    Console.WriteLine("the answer is " + answer);
    return;
}
  • Where are `number1` and `number2` defined? – Arian Motamedi Apr 04 '18 at 15:20
  • 1
    Why are you throwing an exception only to catch it on the very next line? Just do what you want to do when you can't parse the values at the point that you're currently throwing it, instead of throwing an exception. – Servy Apr 04 '18 at 15:21
  • 1
    if `number1` and `number2` get declared outside of `try catch` within the same class, should be able to access them in the `if` – LONG Apr 04 '18 at 15:23
  • 1
    Go check one of these [link1](https://msdn.microsoft.com/en-us/library/ms973875.aspx) [link2](http://www.informit.com/articles/article.aspx?p=1609145&seqNum=4) [link3](http://www.blackwasp.co.uk/CSharpVariableScopes.aspx) [link4](https://stackoverflow.com/questions/1196941/variable-scope-confusion-in-c-sharp). To learn more about variable scope cause it is your problem here. – vincrichaud Apr 04 '18 at 15:24
  • 1
    Why do you want to perform those operations on those values if the numbers were invalid? Those operations don't make any sense to do if the input values weren't valid. – Servy Apr 04 '18 at 15:24

0 Answers0