E
E
elothewizz2019-03-15 21:40:07
C++ / C#
elothewizz, 2019-03-15 21:40:07

How can I shorten the copied code?

There is a code that is responsible for the correct display of numbers in the TextBox

private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (answer != 0)
            {
                AnswerBox.Text = "";
            }
            if (operator1 == 0)
            {
                if (number1 < long.MaxValue)
                {
                    number1 = number1 * 10 + 1;
                    AnswerBox.Text = number1.ToString();
                }
                else AnswerBox.Text = "Error: long overflow";
            }
            else
            {
                if (number2 < long.MaxValue)
                {
                    number2 = number2 * 10 + 1;
                    AnswerBox.Text = number2.ToString();
                }
                else AnswerBox.Text = "Error: long overflow";
            }
        }


Please tell me how to optimize this code. Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
foxlye, 2019-03-16
@elothewizz

Have you tried merge into method?
By type like this:

void name(){
            if (answer != 0)
            {
                AnswerBox.Text = "";
            }
            if (operator1 == 0)
            {
                if (number1 < long.MaxValue)
                {
                    number1 = number1 * 10 + 1;
                    AnswerBox.Text = number1.ToString();
                }
                else AnswerBox.Text = "Error: long overflow";
            }
            else
            {
                if (number2 < long.MaxValue)
                {
                    number2 = number2 * 10 + 1;
                    AnswerBox.Text = number2.ToString();
                }
                else AnswerBox.Text = "Error: long overflow";
            }
}

And then when you click on the button, call this method
name();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question