It feels strange to me to be casting null to a type so I wanted to double check that this is the right way to do this:
decimal? d = data.isSpecified ? data.Value : (decimal?)null;
NOTE: I am marking the answer that suggests the method that I personally like the best:
decimal? d = data.isSpecified ? data.Value : default(decimal?)
Conversion from a nullable value type to an underlying type At run time, if the value of a nullable value type is null , the explicit cast throws an InvalidOperationException.
You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.
A type is said to be nullable if it can be assigned a value or can be assigned null, which means the type has no value whatsoever.
Nullable is a term in C# that allows an extra value null to be owned by a form. We will learn in this article how to work with Nullable types in C#. C# Nullable. In C#, We have majorly two types of data types Value and Reference type. We can not assign a null value directly to the Value data type.
Yes, that's fine. Alternatives:
condition ? (decimal?) value : null
condition ? new decimal?(value) : null
condition ? value : default(decimal?)
condition ? value : new decimal?()
Pick whichever you find most readable.
There's nothing you can do outside the expression itself, as it's the type of the expression which the compiler doesn't know. For example, putting the whole expression in brackets and casting it wouldn't help.
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