0

I am creating a simple calculator app in WinUI with C#. I am using the Compute method in DataTable to solve the arithmetic problem. AnswerBox is a label where numbers and operators are appended, and an answer is displayed (using the compute function) when a button is clicked.

AnswerBox.Text = (string)new DataTable().Compute(AnswerBox.Text, "");

It raises an exception when I enter 2+2 (or any other valid expression) in the label. The exception is not shown in vs2022, the app crashes and opens the App.g.i.cs file showing the following.

#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
            UnhandledException += (sender, e) =>
            {
                if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
            };
#endif 
4
  • 1
    Look at e argument, it will contain the exception causing the crash. Commented Jun 16, 2024 at 16:51
  • 1
    It often helps to actually add the exception you get. They aren't equal you know. Here the result oft "2+2" is an integer and not a string. The exception should tell you that. Commented Jun 16, 2024 at 18:43
  • Apart from anything else, I would expect the exception to be displayed in the Output window, although perhaps it wouldn't happen until you continued from that point. Commented Jun 17, 2024 at 1:38
  • @jmcilhinney, I was expecting that too, but when I continue, it says the current debugger is unable to handle the exception. Now what does that mean? Commented Jun 17, 2024 at 2:53

2 Answers 2

1

In this case, the following code returns an int value, 4 to be specific.

new DataTable().Compute(AnswerBox.Text, "");

The issue is that you can't just cast int to string.

The next code should work:

var dataTable = new DataTable();

if (dataTable.Compute(AnswerBox.Text, "") is int coputeResult)
{
    AnswerBox.Text = coputeResult.ToString();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, @Andrew KeepCoding, I thought that compute converts the int result into string so I used string cast. I would also add an else if statement for decimal (float) as my calculator also has decimal operations :)
-1

I later came up with a better solution -

var result = new DataTable().Compute(AnswerBox.Text, "");
AnswerBox.Text = result.ToString();

Now it can handle both int and decimal (practically anything xD).

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.