Problems using null coalescing

Asked

Viewed 64 times

1

I’m having trouble using the null coalescing in the case below:

When trying to use operand ?? to validate if the value reader["Data"] is void, and if the DateTime.MinValue.

The error that returns is:

Operator ?? cannot be apllied to operands of type 'Datetime' and 'Datetime'

 using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            vendasConfirmadas.Select(v => new Pedido()
                            {                                    
                                Data = Convert.ToDateTime(reader["Data"]) ?? DateTime.MinValue
                            });
                        }
                    }
  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site

1 answer

4

The operator of null coalescing can only be applied on annuadable types, which were standard before C# 8 for types by reference, or if specified in type in any version (could not specify in types by reference before C# 8). The DateTime is a type by value, so it can only be null if explicitly specified, which does not happen with the ToDateDatime().

In fact this code is all wrong if you expect something to go wrong and you shouldn’t even try to do it like that, the right thing would be:

if (!datetime.TryParse(reader["Data"], out var data)) data = DateTime.MinValue;
Data = data;

I put in the Github for future reference.

Behold Differences between Parse() vs Tryparse() and What is the main difference between int. Parse() and Convert.Toint32()?, same goes for date.

On the other hand if you can guarantee that the data is correct there would not need to do anything, because the method ToDateTime() returns exactly what you want if the value to be converted is null, then in your case, if you can guarantee this, and only in this case, do the conversion without using the null check operation, since the method never returns null.

  • 1

    Ah, you’ve helped a lot! Thank you!!

  • 2

    @Demetriuspecoraro see in the [tour] the best way to say thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.