Error 7 The operator '==' cannot be applied to operands of type 'object' and 'bool'

I am converting a lot of code from VB.net to C #, and here is another problem that, it seems to me, arose during the conversion.

if (sRow.Cells[1].Value == true)
    Worked = "X";
else if (sRow.Cells[2].Value == true)
    Vacation = "X";
else if (sRow.Cells[3].Value == true)
    Sick = "X";
else if (sRow.Cells[4].Value == true)
    Holiday = "X";

on every line if / else / else if it gives me this error. I'm sure I miss something that will make me dizzy ...

Error 7 The operator '==' cannot be applied to operands of type 'object' and 'bool'

+5
source share
4 answers

Are you sure these values ​​are of type bool?

If so, just explicitly do:

if ((bool)sRow.Cells[1].Value)
{
    Worked = "X";
}
else if ((bool)sRow.Cells[2].Value)
{
    Vacation = "X";
}
else if (sRow.Cells[3].Value)
{
    Sick = "X";
}
else if ((bool)sRow.Cells[4].Value)
{
    Holiday = "X";
}
+9
source

I assume this is a DataRow cell whose value is of type object. You cannot compare an object with bool with an operator ==.

, Field DataRow:

if(sRow.Field<bool>(1))
    // ...
+5

7 '==' 'object' 'bool'

, :

'==' 'object' 'bool'

Value object, , , .

, , Value , ... . , . - " ..."? , () .

+1

if (x == true), if ((bool)sRow.Cells[1].Value) if (Convert.ToBoolean(sRow.Cells[1].Value)) .

:

if (true.Equals(sRow.Cells[1].Value))
    Worked = "X";
else if (true.Equals(sRow.Cells[2].Value))
    Vacation = "X";
else if (true.Equals(sRow.Cells[3].Value))
    Sick = "X";
else if (true.Equals(sRow.Cells[4].Value))
    Holiday = "X";

: .

, , , .

.

However, casting / conversion is not performed for DBNull, while this approach works:

object x = DBNull.Value;
if (true.Equals(x)); // False
if (Convert.ToBoolean(x)); // InvalidCastException: Object cannot be cast from DBNull to other types.
if ((bool)x); // InvalidCastException: Specified cast is not valid.
+1
source

All Articles