Reputation: 187
I have the code snippet below that I am trying to work with.
decimal preTestAir = decimal.Parse(AirPreTestTextBox.Value);
preTestAir
is a decimal
and needs to remain a decimal
for being sent to the database. This cannot change. What I am trying to do is determine if AirPreTestTextBox.Value
is null, if it is, assign it the decimal
value of 0.00
and then assign it to the decimal
preTestAir
. The code above works great as long as there is some numeric value in the text box. What if there isn't a value in the text box? The app crashes. How can I determine if AirPreTestTextBox.Value
is null and assign a value if it is all in one line? The reason for the one line is because I have almost 100 lines of code that will need to be formatted in this fashion. I've tried using operators like ??
which won't work with decimals that aren't the nullable type. Can anyone help? Any and all help is appreciated!
Upvotes: 1
Views: 3070
Reputation: 61349
Easy enough with a ternary.
decimal preTestAir = String.IsNullOrEmpty(AirPreTestTextBox.Value) ? 0 : decimal.Parse(AirPreTestTextBox.Value);
Its very unlikely that a text box would hold a null
string, its much more likely that its empty.
Upvotes: 4
Reputation: 44298
just use try parse.... it will handle any non convertible to decimal
decimal preTestAir;
if(!deciaml.TryParse(AirPreTestTextBox.Value, out preTestAir))
{
// handle the fact it couldn't convert if you like...
}
Upvotes: 1
Reputation: 5853
The null coalescing operator (??) is your friend here. Use
(AirPreTestTextBox.Value ?? "0.00")
Upvotes: 4
Reputation: 101691
You can simply use the conditional operator:
decimal preTestAir = AirPreTestTextBox.Value == null ?
0.0m :
decimal.Parse(AirPreTestTextBox.Value);
Upvotes: 4