Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default value to null when converting to double in c#

Tags:

c#

I want to pass the null if the string is empty while converting from string to double. Can somebody help me with the syntax? As where I going wrong? Current Syntax:

IngredientMinRange = !string.IsNullOrEmpty(MinRange) ? Convert.ToDouble(MinRange) : null
like image 806
Programmermid Avatar asked Sep 01 '16 14:09

Programmermid


People also ask

Can we assign null to double?

null can only be assigned to reference type, you cannot assign null to primitive variables e.g. int, double, float, or boolean.

What is the default value of null?

The value produced by setting all value-type fields to their default values and all reference-type fields to null . An instance for which the HasValue property is false and the Value property is undefined. That default value is also known as the null value of a nullable value type.

How do you handle a double null in C#?

double is a value type, which means it always needs to have a value. Reference types are the ones which can have null reference. So, you need to use a "magic" value for the double to indicate it's not set (0.0 is the default when youd eclare a double variable, so if that value's ok, use it or some of your own.


2 Answers

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);
like image 80
Tim Schmelter Avatar answered Oct 23 '22 12:10

Tim Schmelter


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

like image 2
Matthias Burger Avatar answered Oct 23 '22 10:10

Matthias Burger