Set default value to null when converting to double in c#
A double
cannot be null
since it's a value- and not a reference type. You could use a Nullable<double>
instead:
double? ingredientMinRange = null;
if(!string.IsNullOrEmpty(MinRange))
ingredientMinRange = Convert.ToDouble(MinRange);
If you later want the double
value you can use the HasValue
and Value
properties:
if(ingredientMinRange.HasValue)
{
double value = ingredientMinRange.Value;
}
Using Nullable Types (C# Programming Guide)
If IngredientMinRange
is already a Double?
-property as commented you can assign the value either via if
(as shown above) or in in one line, but then you have to cast the null
:
IngredientMinRange = string.IsNullOrEmpty(MinRange) ? (double?)null : Convert.ToDouble(MinRange);
to assign null
to a double you have to use Nullable<double>
or double?
. Assign it with this method here:
decimal temp;
decimal? IngredientMinRange = decimal.TryParse(MinRange, out temp) ? temp : (decimal?)null;
then you can continue working with IngredientMinRange
. You get the value with IngredientMinRange.Value
or check if it's null with IngredientMinRange.HasValue