David Bernhardt
David Bernhardt
CC#
Created by David Bernhardt on 10/19/2023 in #help
❔ Why I can´t use TryParse with a ternary if
It´s a really novice question but I don´t get why this works fine with a normal if:
string[] values = { "12,3", "45", "ABC", "11", "DEF" };

decimal total = 0;
string msg = "";
foreach (string value in values)
{
decimal parsedValue;

if (decimal.TryParse(value, out parsedValue))
{
total += parsedValue;
}
else
{
msg += value;
}
}

Console.WriteLine($"Total: {total}");
Console.WriteLine($"Message: {msg}");
string[] values = { "12,3", "45", "ABC", "11", "DEF" };

decimal total = 0;
string msg = "";
foreach (string value in values)
{
decimal parsedValue;

if (decimal.TryParse(value, out parsedValue))
{
total += parsedValue;
}
else
{
msg += value;
}
}

Console.WriteLine($"Total: {total}");
Console.WriteLine($"Message: {msg}");
But replacing it with
decimal.TryParse(value, out parsedValue) ? total += parsedValue : msg += value;
decimal.TryParse(value, out parsedValue) ? total += parsedValue : msg += value;
Does not work
18 replies