Share via

Setting a Datetime to null

Brown, Matt 146 Reputation points
2025-07-30T15:02:56.1866667+00:00

I'm reading in data from a table. For each field I check to see if the value is null and how to handle it. Some of the DateTime fields can be null, see a field for when a request has been reassigned. Here's the code I have below.

public static DateTime? GetDateTime(SqlDataReader reader, int colIndex)
{    
    if (!reader.IsDBNull(colIndex))
        return reader.GetDateTime(colIndex);
    return null;
}

The issue is that this generates an error for when I call said function for each DateTime field regardless if the field is nullable or not. The error is it cannot convert DateTime? to DateTime.

GetDateTime(reader, 115), // DateReassigned
public DateTime? DateReassigned { get; set; }

I do not want any min date in the field as that would imply something happened even when it didn't.

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


3 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,606 Reputation points Volunteer Moderator
    2025-08-01T16:00:00.8866667+00:00

    I recommend using Dapper to read all data and decide what to do with null DateTime. In the following example, the column BirthDate default value is NULL.

    This is done with NET 8 Core Framework.

    public class DataOperations
    {
    
        public static async Task<List<DateTimeWithNulls>> ReadDataAsync()
        {
            string connectionString = "Data Source=(localdb)\\MSSQLLocalDB;" +
                                      "Initial Catalog=Karen1;Integrated Security=True;Encrypt=False";
    
            const string sql = "SELECT Id,BirthDate FROM dbo.DateTimeWithNulls";
    
            await using var connection = new SqlConnection(connectionString);
            return (await connection.QueryAsync<DateTimeWithNulls>(sql)).ToList();
    
        }
    }
    
    public class DateTimeWithNulls
    {
        public int Id { get; set; }
        public DateTime? BirthDate { get; set; }
    }
    

    Usage

    try
    {
        var results = await DataOperations.ReadDataAsync();
        foreach (var item in results)
        {
            if (item.BirthDate is null)
            {
                // TODO: Handle null BirthDate
            }
        }
    }
    catch (Exception exception)
    {
        // Log the exception or show a message to the user
    }
    

    Was this answer helpful?

    1 person found this answer helpful.
    0 comments No comments

  2. Bruce (SqlWork.com) 84,071 Reputation points
    2025-07-30T15:14:40.8666667+00:00

    C# is a strongly typed language, you can not assign a nullable value type to a non nullable variable. You need code to handle null. You use a cast, which will throw an error if the value is not null. Or use if statement to test for null.

    // throw error if null
    var d = (DateTime) GetDateTime(reader, 115);
    

    Was this answer helpful?

    1 person found this answer helpful.
    0 comments No comments

  3. Starry Night 625 Reputation points
    2025-08-05T02:34:15.39+00:00

    I do not want any min date in the field as that would imply something happened even when it didn't.

    The DateTime.MinValue field in .Net represents the smallest possible value of a DateTime object. It is equivalent to 00:00:00.0000000 UTC, January 1, 0001, in the Gregorian calendar. When a DateTime variable is declared but not initialized, it defaults to DateTime.MinValue.

    We usually need to ensure that any custom date value is greater than or equal to DateTime.MinValue to avoid exceptions when creating DateTime instances.

    So, we usually do like this:

    `public DateTime? DateReassigned { get; set; } = DateTime.MinValue ;`
    

    Of course, you can also use the null-coalescing operators,which is designed for exactly this purpose.

     `DateReassigned = ssrDAO.GetDateTime(reader, 115) ?? DateTime.MinValue;`
    

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.