I can't understand why this won't work
decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) ? decimal.Parse(txtLineCompRetAmt.Text.Replace(",","")) : null;
All replies. Yes, the syntax is for a nullable type in C# is... As long as you're using C# v6 then you can use the suggestions mentioned.
NET Platform) concepts. This means that C# value type equivalents in the database, such as int, decimal, and DateTime, can be set to null.
In C#, you can assign the null value to any reference variable. The null value simply means that the variable does not refer to an object in memory. You can use it like this: Circle c = new Circle(42); Circle copy = null; // Initialized ... if (copy == null) { copy = c; // copy and c refer to the same object ... }
As you know, a value type cannot be assigned a null value. For example, int i = null will give you a compile time error. C# 2.0 introduced nullable types that allow you to assign null to value type variables. You can declare nullable types using Nullable<t> where T is a type.
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.
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.
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