Search code examples
c#.net-3.5c#-3.0asmxasp.net-3.5

Getting "no implicit conversion between '<null>' and 'System.DateTime'" error message


In a previous question:

Getting "This method or property cannot be called on Null values" error

I had a problem with the following code:

client_group_details.Add(new ClientGroupDetails(
    reader.GetString(Col2Index),
    reader.GetString(Col3Index)));

Where I was getting the following error:

Data is Null. This method or property cannot be called on Null values.

This problem was resolved using the following code:

client_group_details.Add(new ClientGroupDetails(
    reader.IsDbNull(Col2Index) ? null : reader.GetString(Col2Index),
    reader.IsDbNull(Col3Index) ? null : reader.GetString(Col3Index)));

I now have a similar problem with GetDateTime and GetInt32, as example is:

client_group_details.Add(new ClientGroupDetails(
    reader.GetString(Col2Index),
    reader.GetString(Col3Index),
    reader.GetDateTime(Col4Index)));

I tried using the following to resolve this problem, but it didn't work

client_group_details.Add(new ClientGroupDetails(
    reader.IsDbNull(Col2Index) ? null : reader.GetString(Col2Index),
    reader.IsDbNull(Col3Index) ? null : reader.GetString(Col3Index),
    reader.IsDbNull(Col2Index) ? null : reader.GetDateTime(Col4Index)));

It gives the error:

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

After searching for a solution, I found: Nullable type issue with ?: Conditional Operator. But when I try to use that code, I keep getting ) expected.

How would I resolve this problem?


Solution

  • You are missing a closing bracket somewhere.

    client_group_details.Add(new ClientGroupDetails(
        reader.IsDbNull(Col2Index) ? null : reader.GetString(Col2Index),
        reader.IsDbNull(Col3Index) ? null : reader.GetString(Col3Index),
        reader.IsDbNull(Col2Index) ? null : reader.GetDateTime(Col4Index)));
    

    Should probably change to

    client_group_details.Add(new ClientGroupDetails(
        reader.IsDbNull(Col2Index) ? null : reader.GetString(Col2Index),
        reader.IsDbNull(Col3Index) ? null : reader.GetString(Col3Index),
        reader.IsDbNull(Col2Index) ? (DateTime?)null : reader.GetDateTime(Col4Index)));
    

    or something similar. Depending on your exact code someone will be able to tell you where the missing bracket it.