1

I'm new to C# but not to programming in general. I am trying to set add some error checking to my program. There are 3 textboxes and I am trying to make it so that if the text box is left blank, it assumes a value of 0. Here is my code so far:

    private void btnCalculate_Click(object sender, EventArgs e)
    {
        if (String.IsNullOrEmpty(txtNumberOfClassATix.Text))    // Assumes 0 if no number entered for txtNumberOfClassATix.Text.
        {
            txtNumberOfClassATix.Text = "0";
        }
        if (String.IsNullOrEmpty(txtNumberOfClassBTix.Text))    // Assumes 0 if no number entered for txtNumberOfClassBTix.Text.
        {
            txtNumberOfClassBTix.Text = "0";
        }
        if (String.IsNullOrEmpty(txtNumberOfClassCTix.Text))    // Assumes 0 if no number entered for txtNumberOfClassCTix.Text.
        {
            txtNumberOfClassCTix.Text = "0";
        }
        int classANum = int.Parse(txtNumberOfClassATix.Text);
        int classBNum = int.Parse(txtNumberOfClassBTix.Text);
        int classCNum = int.Parse(txtNumberOfClassCTix.Text);
        double classATotal = classANum * classAPrice;
        double classBTotal = classBNum * classBPrice;
        double classCTotal = classCNum * classCPrice;
        lblCalculatedClassARevenue.Text = $"{classATotal:c}";
        lblCalculatedClassBRevenue.Text = $"{classBTotal:c}";
        lblCalculatedClassCRevenue.Text = $"{classCTotal:c}";
        lblCalculatedTotalRevenue.Text = $"{(classATotal + classBTotal) + classCTotal:c}";
    }

This code works but I'm sure I could replace those if statements with something simpler. I've seen how to set a variable to null if another is null using the null-conditional operator but I don't really grasp it enough to adapt it to my scenario.

3
  • You could use TryParse instead and use 0 if it fails. int classANum = int.TryParse(txtNumberOfClassATix.Text, out var val1) ? val1 : 0; Then you can remove all the code above the parsing. Commented Jan 30, 2018 at 20:52
  • 1
    The null conditional operator only works with null values, not empty string or whitespace values. Commented Jan 30, 2018 at 20:53
  • I suggest you write a function along the lines of int parseNumber(String text) { return String.IsNullOrEmpty(text) ? 0 : int.Parse(text); }. Think about how to treat invalid input other than empty strings too. Commented Jan 30, 2018 at 20:55

4 Answers 4

3

So far maccettura's answer is the best, but can we do better? Sure we can. Let's make a general-purpose extension method:

internal static class Extensions 
{
  public static int? AsInt(this string s)
  {
    int result;
    if (s == null)
      return null;
    else if (int.TryParse(s, out result))
      return result;
    else
      return null;
  }
}

And now:

    int classANum = txtNumberOfClassATix.Text.AsInt() ?? 0;

If it's an int, you get the int. If it's not, you get zero. Easy peasy.

Or, you might want this extension method:

internal static class Extensions 
{
  public static int AsInt(this string s, int default = 0)
  {
    int result;
    if (s == null)
      return default;
    else if (int.TryParse(s, out result))
      return result;
    else
      return default;
  }
}

And now you can say what you want the default to be without using ??.

This style of programming is called "fluent programming"; it can make code that is very easy to read and understand.

Notice that this solution does not update the UI with zeros; if you wanted to do that then I would recommend splitting that into two steps: one which causes the mutation, and then a separate step which computes the value. Operations which are useful for both their effects and their values can be confusing.

Sign up to request clarification or add additional context in comments.

Comments

1

This is a perfect time to use a method so you arent repeating yourself:

private static int GetInputAsInt(TextBox textbox)
{
    int outputValue = 0;
    if(textbox?.Text != null && int.TryParse(textbox.Text, out outputValue))
    {  
        return outputValue;
    }
    return 0;
}

Now you are checking if the textbox itself is not null, and that the value contained therein is a int, if anything fails it returns a 0;

Call it in your other method like this:

int classANum = GetInputAsInt(txtNumberOfClassATix);

Which means your button click event would be a bit simpler:

private void btnCalculate_Click(object sender, EventArgs e)
{
    int classANum = GetInputAsInt(txtNumberOfClassATix);
    int classBNum = GetInputAsInt(txtNumberOfClassBTix);
    int classCNum = GetInputAsInt(txtNumberOfClassCTix);
    double classATotal = classANum * classAPrice;
    double classBTotal = classBNum * classBPrice;
    double classCTotal = classCNum * classCPrice;
    lblCalculatedClassARevenue.Text = $"{classATotal:c}";
    lblCalculatedClassBRevenue.Text = $"{classBTotal:c}";
    lblCalculatedClassCRevenue.Text = $"{classCTotal:c}";
    lblCalculatedTotalRevenue.Text = $"{(classATotal + classBTotal) + classCTotal:c}";
}

Comments

0

To keep it simple, a good approach is to use the conditional operator. The full example is below (broken across two lines for readability):

txtNumberOfClassATix.Text = 
    String.IsNullOrEmpty(txtNumberOfClassATix.Text) ? "0" : txtNumberOfClassATix.Text;

This is a nice, readable, assignment for the first part:

myString = ...

The conditional operator breaks down by providing a boolean expression (true/ false) on the left side of the ?. So, for example:

myString = anotherString == "" ? ... // checking if another string is empty

The final part is the :. To the left is the assignment if the expression is true, and to the right goes the assignment if the expression is false. To finish the example:

myString = anotherString == "" ? "anotherString is empty" : "anotherString is not empty";

The above example can be written out in full to clear up any misunderstanding as:

if (anotherString == "")
{
    myString = "anotherString is empty";
}
else
{
    myString = "anotherString is not empty";    
}

This can apply to all the statements. The documentation is found here.

Comments

0

The best way to reduce the line of code is use the function for your common operation(s). In your case, you can create function which checks whether or not the object is NULL or empty. Based on the return value of that function you can proceed ahead. On the other hand, you can handle it on front-end by using different validators such as RequiredFieldValidator, CustomValidator, etc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.