Zo Has
Zo Has

Reputation: 13028

Why can't I assign null to decimal with ternary operator?

I can't understand why this won't work

decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) 
    ? decimal.Parse(txtLineCompRetAmt.Text.Replace(",","")) 
    : null;

Upvotes: 26

Views: 55113

Answers (6)

slugster
slugster

Reputation: 49984

Because null is of type object (effectively untyped) and you need to assign it to a typed object.

This should work:

decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) 
         ? decimal.Parse(txtLineCompRetAmt.Text.Replace(",","")) 
         : (decimal?)null;

or this is a bit better:

decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) 
         ? decimal.Parse(txtLineCompRetAmt.Text.Replace(",","")) 
         : default(decimal?);

Here is the MSDN link for the default keyword.

Upvotes: 65

juergen d
juergen d

Reputation: 204766

Try this:

decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) ? 
                         decimal.Parse(txtLineCompRetAmt.Text.Replace(",", "")) : 
                         (decimal?) null;

The problem is that the compiler does not know what type nullhas. So you can just cast it to decimal?

Upvotes: 5

Ebad Masood
Ebad Masood

Reputation: 2379

Don't use decimal.Parse.

Convert.ToDecimal will return 0 if it is given a null string. decimal.Parse will throw an ArgumentNullException if the string you want to parse is null.

Upvotes: 7

Jakub Konecki
Jakub Konecki

Reputation: 46008

You need to cast the first part to decimal?

decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) 
    ? (decimal?)decimal.Parse(txtLineCompRetAmt.Text.Replace(",","")) 
    : null;

Upvotes: 2

Thomas Levesque
Thomas Levesque

Reputation: 292455

Because the compiler can't infer the best type from the operands of the conditional operator.

When you write condition ? a : b, there must be an implicit conversion from the type of a to the type of b, or from the type of b to the type of a. The compiler will then infer the type of the whole expression as the target type of this conversion. The fact that you assign it to a variable of type decimal? is never considered by the compiler. In your case, the types of a and b are decimal and some unknown reference or nullable type. The compiler can't guess what you mean, so you need to help it:

decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text)
                             ? decimal.Parse(txtLineCompRetAmt.Text.Replace(",",""))
                             : default(decimal?);

Upvotes: 3

vc 74
vc 74

Reputation: 38179

decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) ?  
                          decimal.Parse(txtLineCompRetAmt.Text.Replace(",","")) : 
                          (decimal?)null;

Upvotes: 3

Related Questions