How to use double.TryParse when the output is allowed to be 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;
    }