L
L
libera2016-02-19 20:04:52
C++ / C#
libera, 2016-02-19 20:04:52

C# code reduction?

Banal addition of 2 numbers

int a = Convert.ToInt32(textBox.Text);
            int b = Convert.ToInt32(textBox1.Text);
            label.Content = a + b;

Is there any way to reduce the code?
An example is not to drive 2 variables, and write data to them, then add and output.
of type label.Content = textBox.Text + textBox1.Text;
Only with conversion from string to int

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Nemiro, 2016-02-19
@libera

label.Content = (Convert.ToInt32(textBox.Text) + Convert.ToInt32(textBox1.Text)).ToString();

Or write a function and use it:
private static string Sum(string a, string b)
{
  return (Convert.ToInt32(a) + Convert.ToInt32(b)).ToString();
}

Or even like this:
label.Content = Sum(textBox.Text, textBox1.Text);
label.Content = Sum(textBox.Text, textBox1.Text, textBox2.Text, textBox4.Text);

private static string Sum(params string[] n)
{
  return n.Sum(itm => Convert.ToInt32(itm)).ToString();
}

You can also write an extension, but this is only in case the addition of numbers in the TextBox is frequent in the project :-)
public static class TextBoxExtension
{

  public static string SumWith(this TextBox value, params TextBox[] n)
  {
    return (Convert.ToInt32(value.Text) + n.Sum(itm => Convert.ToInt32(itm.Text))).ToString();
  }

}

Either extend string :
public static class StringExtension
{

  public static string SumWith(this string value, params string [] n)
  {
    return (Convert.ToInt32(value) + n.Sum(itm => Convert.ToInt32(itm))).ToString();
  }

}

label.Content = textBox.Text.SumWith(textBox1.Text);

M
Melz, 2016-02-19
@melz

Don't use Convert.ToInt32.
You need Int32.TryParse. There, the format can be substituted, and in case of input errors, the exceptions will not be strewed.
If you want beautifully - do it through bindings, events and other MVVM.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question