Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

I can't understand why this won't work

decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text)      ? decimal.Parse(txtLineCompRetAmt.Text.Replace(",",""))      : null; 
like image 696
Zo Has Avatar asked Feb 16 '12 09:02

Zo Has


People also ask

Can we assign null to decimal in C#?

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.

Can a decimal be null?

NET Platform) concepts. This means that C# value type equivalents in the database, such as int, decimal, and DateTime, can be set to null.

How to assign null in C#?

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 ... }

How to make integer Nullable in C#?

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.


2 Answers

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.

like image 76
slugster Avatar answered Oct 05 '22 01:10

slugster


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.

like image 44
Ebad Masood Avatar answered Oct 04 '22 23:10

Ebad Masood