January 2, 2008

.NET Compiler bug? (Update)

I have a typed DataTable (called FactTable) that gets data from a table in SQL server where a Date field can be null.

So I have created a System.Nullable variable in my code:
Datetime? emailDate;

And a typed DataRow from my DataTable:
MyDataSet.FactRow factRow = factTable.Rows[0];

Why does this NOT WORK:
emailDate = factRow.IsEmailDateNull() ? null : factRow.EmailDate;

But this works:
if (factRow.IsEmailDateNull())
emailDate = null;
else
emailDate = factRow.EmailDate;



Compiler error is: Type of conditional expression cannot be determined because there is no implicit conversion between '' and 'System.DateTime'

Remember: My variable is nullable!!!

Update:
David defined this problem as a feature. But aren't both examples the same? Isn't this just a compile thing to convert from the first example to the second one?
I think it has to do something with nullable types, because with string or byte[] it works like a charm:
string title = factRow.IsTitleNull() ? null : factRow.Title;
byte[] picture = factRow.IsPictureNull() ? null : factRow.Picutre;

3 comments:

David Vidmar said...

Feature, not a bug. :)

It will not work. When using ? operator booth sides of ? has to been of the same type. They are not in your case, since null doesn't have a type.

http://channel9.msdn.com/ShowPost.aspx?PostID=191003

Dejan Dular said...

Then why does this work?

string title = factRow.IsTitleNull() ? null : factRow.Title;

Dejan Dular said...

Ok. I found a solution. Cast null to (DateTime?) type:

emailDate = factRow.IsEmailDateNull() ? (DateTime?)null : factRow.EmailDate;