简体   繁体   中英

Can't test on System.Boolean

This

row["active"].GetType().ToString()

evals to

System.Boolean

Why is this an error?

if (row["active"]) { ... }
if (row["active"] == true) { ... }

I would think that a System.Boolean could be true or false?

The return type of row["active"] is an object, which isn't valid as a boolean predicate. That the value returned is actually a wrapped boolean doesn't matter.

You know that it is a boolean, but the compiler doesn't. What if row["active"] would suddenly return a string? Than the expression would be invalid. The .NET runtime binds variables early, on compile time. It doesn't evaluate their types on runtime, like some dynamic languages do.

You have to tell the compiler the value is a boolean by casting it:

if ((bool)row["active"]) { ... }

row[string] returns type object , not boolean and the if block will not automatically convert to type boolean .

You could cast yourself like this.

if ((bool) row["active"]) { ... }

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