How to use double.TryParse when output is allowed as null?

In my application, I have a text field - txtDiscount , where the administrator can set the discount percentage for a specific user, or he may not be. At the back end, I want to save the data, so 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 message for invalid argument and obviously this is a discount , which cannot be NULL if I am going to use it in TryParse . I saw that many people make extensions for such situations, but so far I do not think it is necessary. What I can think of is to use another variable:

 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 in fact, I do not like the code above, it seems to me that it is quite difficult for such a task, but I can not come up with something better. So, how can I handle this situation without using the extension method?

+6
source share
6 answers

You can parse without an extension method - just use a non-zero local value to pass it to the 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 moved all this logic to extension.

+4
source

You just have to write ugly code with a local non-empty type, or use another way to determine if there is no discount. I agree that a double key is a neat way of representing it, but if the code annoys you, try something else (bool, for example: discount_given = true ).

Personally, I just go with an extension that parses a nullable double value:

  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; } 
+3
source
 static void Main() { var testStrings = new[] { "", "1.234" }; foreach( var testString in testStrings ) { double output; double? value = null; if( double.TryParse( testString, out output ) ) { value = output; } Console.WriteLine( "{0}", value.HasValue ? value.Value.ToString() : "<null>" ); } } 
+1
source
  public static double ToDouble(this string value, double fallbackValue = 0) { double result; return double.TryParse(value, out result) ? result : fallbackValue; } 
0
source
 Nullable<double> discount = new Nullable<double>(); 

the default value is allready null, you do not need to set it to null again

-1
source
 if(double.TryParse(txtDiscount.Text?? "", out _discount)) discount=_discount; else Console.WriteLine("Discount must be adouble."); 
-1
source

All Articles