Can I cast from DBNull to a Nullable Bool in one line?

后端 未结 5 793
南笙
南笙 2021-02-19 04:37

I have a database query which will either return NULL or a boolean (bit) value.

I wish to store this value in a variable of type Nullable<

5条回答
  •  半阙折子戏
    2021-02-19 04:55

    assuming you have a datareader dr:

    bool? tmp = Convert.IsDBNull(dr["dbnullValue"]) ? null: (bool?) dr["dbnullValue"];
    

    ---ADDED----

    or maybe you can use the ?? if you don't have to check for DBNull but i'm not sure compiler will like this (i cannot test it now)

    bool? tmp = dr["dbnullValue"] ?? (bool?) dr["dbnullValue"];
    

提交回复
热议问题