Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# ?? null coalescing operator question

I have defined Class Person property Birthday as nullable DateTime? , so why shouldn’t the null coalescing operator work in the following example?

cmd.Parameters.Add(new SqlParameter("@Birthday",
   SqlDbType.SmallDateTime)).Value =       
     person.Birthday ?? DBNull.Value; 

The compiler err I got was "Operator '??' cannot be applied to operands of type 'System.DateTime?' and 'System.DBNull'"

The following also got a compile error :

cmd.Parameters.Add(new SqlParameter("@Birthday", 
  SqlDbType.SmallDateTime)).Value = 
   (person.Birthday == null) ? person.Birthday:DBNull.Value;

I added a cast to (object) as recommended by Refactor, and it compiled, but didn’t work properly and the value was stored in the sqlserver db as null in both cases.

SqlDbType.SmallDateTime)).Value =       
         person.Birthday ?? (object)DBNull.Value;

Can someone explain what is going on here?

I needed to use the following clumsy code:

   if (person.Birthday == null) 
    cmd.Parameters.Add("@Birthday", SqlDbType.SmallDateTime).Value 
      = DBNull.Value;
     else cmd.Parameters.Add("@Birthday", SqlDbType.SmallDateTime).Value = 
          person.Birthday;
like image 327
Lill Lansey Avatar asked Aug 06 '10 15:08

Lill Lansey


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


1 Answers

The problem is that DateTime? and DBNull.Value are not the same type so you can't use the null coalescing operator on them.

In your case you can do person.Birthday ?? (object)DBNull.Value to pass a value of type object through to Add()

like image 193
Dave D Avatar answered Oct 09 '22 22:10

Dave D