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
null can only be assigned to reference type, you cannot assign null to primitive variables e.g. int, double, float, or boolean.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With