简体   繁体   中英

Proper bool definition as non-nullable operator

var account = new TRANSPORT_TO_ACCOUNT
{
    TransportLayerId = reader["ID"] as string,
    ...
    BLOCKED = reader["BLOCKED"] as bool,
};
accounts.Add(account);

I've had a problem with this code.

The as operator must be used with a reference type or nullable type ('bool' is a non-nullable value type)

How should I declare the BLOCKED properly in this case?

If you are sure the property is a bool , then just cast it:

var account = new TRANSPORT_TO_ACCOUNT
              { TransportLayerId = (string)reader["ID"]
              , BLOCKED = (bool)reader["BLOCKED"]
              };

accounts.Add(account);

Or if you are not sure is has a value or not:

, BLOCKED = (bool?)reader["BLOCKED"]

Or if you are not even sure it is a (nullable) boolean field:

, BLOCKED = reader["BLOCKED"] as bool?

And if reader is a DbDataReader , you could use GetBoolean , as Rene Vogt suggested.

As a side note: you should work on your naming conventions. Properties and classes should be camel cases, so it would be Blocked and TransportToAccount .

If your reader is some derivate of DbDataReader (for example a SqlDataReader ) you could use IsDbNull() and GetBoolean() :

int blockedIndex = reader.GetOrdinal("BLOCKED");
var account = new TRANSPORT_TO_ACCOUNT
{
    TransportLayerId = reader["ID"] as string,
    ...
    BLOCKED = reader.IsDbNull(blockedIndex) 
                ? (bool?)null 
                : reader.GetBoolean(blockedIndex)
};
accounts.Add(account);

Since IsDbNull and GetBoolean use the column index as parameter instead of the column name, you'd want to cache the index using GetOrdinal first.

And as Patrick already suggested, try to improve your naming conventions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM