I can\'t understand why this won\'t work
decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text)
? decimal.Parse(txtLineCompRetAmt.Text.R
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?);
You need to cast the first part to decimal?
decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text)
? (decimal?)decimal.Parse(txtLineCompRetAmt.Text.Replace(",",""))
: null;
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.
decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) ?
decimal.Parse(txtLineCompRetAmt.Text.Replace(",","")) :
(decimal?)null;
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.
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 null
has. So you can just cast it to decimal?