Search code examples
c#castingbooleandatareader

How to cast a null boolean from the datareader in C#?


I am trying to cast a null boolean from the database using this method:

bool? primaryFlag = reader["primaryflag"] is DBNull ? null: (bool?)reader["primaryflag"];

I keep getting a Specified Cast Invalid Exception. What is wrong with the method I'm using?


Solution

  • You cannot cast it to a Nullable<bool> directly. But you can use the as operator:

    bool? primaryFlag = reader["primaryflag"] as bool?;
    

    This works because the cast fails if the value is DBNull.Value, so it will correctly assign a bool? that is null.

    or this less elegant version:

    bool? primaryFlag = null;
    int colOrdinal = reader.GetOrdinal("primaryflag");
    if(!reader.IsDBNull(colOrdinal))
        primaryFlag = reader.GetBoolean(colOrdinal);