In my application I have a textbox - txtDiscount
where the admin can set a discount percentage for a certain user, or he may not. On the back end I want to save the data so for now I have this:
double? discount = null;
if (!string.IsNullOrEmpty(txtDiscount.Text))
{
if (!double.TryParse(txtDiscount.Text, out discount)) errors.Add("Discount must be a double.");
}
So I get an error for invalid argument
and obviously it's the discount
which can not be nullable if I'm gonna use it in TryParse
. I saw that many people are making extensions for this type of situations but for now I don't think it's necessary. What I can think of is using another variable like so :
double? discount = null;
private double _discount;
if (!string.IsNullOrEmpty(txtDiscount.Text))
{
if (!double.TryParse(txtDiscount.Text, out _discount))
{
errors.Add("Discount must be adouble.");
}
else
{
discount = _discount;
}
}
and then use my nullable discount
to pass the value to the database. But I actually don't like the code above, it seems to me pretty complicated for such a task but I can't think of something better. So how can I deal with this situation without using extension method?
I know it is an old question, but with the new versions of C# it is possible to use this way:
double? discount;
discount = (double.TryParse(myValueToParse, out double myParsedDouble) ? myParsedDouble : null);
In this way, you try to parse to the local variable myParseddouble. If it is possible, it is assigned as value, if not, it set to null.
You can do parsing without extension method - just use local non-nullable value to pass it to TryParse method:
double? discount = null;
if (!String.IsNullOrEmpty(txtDiscount.Text))
{
double value;
if (Double.TryParse(txtDiscount.Text, out value))
discount = value;
else
errors.Add("Discount must be a double."); // discount will have null value
}
But I'd moved all this logic to extension.
You're just going to have to write the ugly code with a local non-nullable type or use another way of defining that there's no discount. I agree that a nullable double is a neat way of representing it, but if the code annoys you so then try something different (a bool, for example: discount_given = true
).
Personally, I'd just go with an extension that parses to nullable double:
public static bool ParseDouble(string s, out double? dd)
{
double d;
bool ret = double.TryParse(s, out d);
if (ret)
dd = d;
else
dd = null;
return ret;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With