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

Leron_says_get_back_Monica picture Leron_says_get_back_Monica · Jan 24, 2014 · Viewed 10.4k times · Source

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?

Answer

Sergey Berezovskiy picture Sergey Berezovskiy · Jan 24, 2014

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.