Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it right to cast null to nullable when using ternary expression assigning to a nullable type?

Tags:

c#

nullable

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;

alt text

alt text

NOTE: I am marking the answer that suggests the method that I personally like the best:

decimal? d = data.isSpecified ? data.Value : default(decimal?)
like image 397
Aaron Anodide Avatar asked Oct 29 '10 16:10

Aaron Anodide


People also ask

Can a nullable be null?

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.

What is use nullable type declare a variable with nullable type?

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.

What is difference between null and nullable?

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.

What is nullable property in C#?

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.


1 Answers

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.

like image 113
Jon Skeet Avatar answered Oct 06 '22 00:10

Jon Skeet