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

后端 未结 6 846
故里飘歌
故里飘歌 2021-01-17 08:03

I can\'t understand why this won\'t work

decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) 
    ? decimal.Parse(txtLineCompRetAmt.Text.R         


        
相关标签:
6条回答
  • 2021-01-17 08:13

    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?);
    
    0 讨论(0)
  • 2021-01-17 08:17

    You need to cast the first part to decimal?

    decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) 
        ? (decimal?)decimal.Parse(txtLineCompRetAmt.Text.Replace(",","")) 
        : null;
    
    0 讨论(0)
  • 2021-01-17 08:18

    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.

    0 讨论(0)
  • 2021-01-17 08:20
    decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) ?  
                              decimal.Parse(txtLineCompRetAmt.Text.Replace(",","")) : 
                              (decimal?)null;
    
    0 讨论(0)
  • 2021-01-17 08:38

    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.

    0 讨论(0)
  • 2021-01-17 08:40

    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?

    0 讨论(0)
提交回复
热议问题