Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning `null` value to Nullable<DateTime> with single line 'if'

Tags:

c#

datetime

null

I have a Class like this

public class MyClass {     public int Id { get; set; }     public Nullable<DateTime> ApplicationDate { get; set; }     .... } 

Now I'm trying to fill an object of MyClass like this

DataTable dt = DBHelper.GetDataTable(sql, conn); DataRow dr = dt.Rows[0];  MyClass oMyClass = new MyClass(); oMyClass.Id = (int)dr["Id"]; oMyClass.ApplicationDate = dr["ApplDate"] == DBNull.Value ? null : Convert.ToDateTime(dr["AppDate"]);  //Above line gives an error .... 

Assigning of Application Date value gives an error

Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'System.DateTime'

What am I missing here?

like image 211
Nalaka526 Avatar asked Oct 12 '12 08:10

Nalaka526


People also ask

How do you handle null in DateTime?

The Nullable < T > structure is using a value type as a nullable type. By default DateTime is not nullable because it is a Value Type, using the nullable operator introduced in C# 2, you can achieve this. Using a question mark (?) after the type or using the generic style Nullable.

Can we assign null to DateTime in C#?

CSharp Online TrainingUsing the DateTime nullable type, you can assign the null literal to the DateTime type. A nullable DateTime is specified using the following question mark syntax.

How do I assign a null to a nullable integer?

As described above, The Nullable types used to assign the null value to the value data type. That means we can assign a null value directly to a variable of the value data type. We can declare null value using Nullable<T> where T is a type like an int, float, bool, etc.

Can DateTime be nullable?

DateTime CAN be compared to null; It cannot hold null value, thus the comparison will always be false. DateTime is a "Value Type". Basically a "value type" can't set to NULL. But by making them to "Nullable" type, We can set to null.


1 Answers

You need to cast null to DateTime?:

oMyClass.ApplicationDate = dr["ApplDate"] == DBNull.Value      ? (DateTime?)null      : Convert.ToDateTime(dr["AppDate"]);  

This is because of the way the compiler determines the resulting type of the conditional operator; the behavior is by design:

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

Since null by itself is of null type and thus there is no conversion from or to it, you need to help the compiler by casting.

like image 52
Jon Avatar answered Oct 22 '22 21:10

Jon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!