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
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();
}