Velu Prabhakar
Velu Prabhakar

Reputation: 11

AND operation in C#

I want to perform an AND operation. My inputs are 2 objects. It could be a string like "true" or it could be an expression like "1==1" as well. When using && operator, am getting an exception that String was not recognized as a valid boolean.

Please help me.

return Convert.ToBoolean(obj[0]) && Convert.ToBoolean(obj[1]);

Sorry for the earlier post which was not clear enough.

Upvotes: 1

Views: 194

Answers (5)

ZubinAmit
ZubinAmit

Reputation: 76

First make sure obj[0], obj[1] will only contain 1 or 0(char or integer). Because Convert.ToBoolean does not understand anything other than 1 or 0.

Upvotes: 1

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60694

Converting "1==1" to a boolean is not possible for the Convert.ToBoolean method. It just converts the strings true and false.

You will have to either write a expression evaluator yourself, or use some kind of library to parse your string to a boolean (like Flee for example)

Upvotes: 3

Jite
Jite

Reputation: 5847

Why use a string? The conversion will not evaluate code, it will check if the supplied data is possible to convert to a bool and do so if possible.

Your function will always return true if it was working, cause 1 is always equal to 1, and true is always true.

Upvotes: 0

Gun
Gun

Reputation: 1411

The below one will work

Convert.ToBoolean(true) && Convert.ToBoolean(1==1)

Upvotes: 0

Johnny_D
Johnny_D

Reputation: 4652

This is nearly impossible as C# is strongly type language. What you trying to do is for weakly types languages like JS. "1==1" will work for JS, not for C#. Remove quotes in order to make it work(You might as well remove first operand, as it doesn't make any sense):

return ( 1 == 1 );

Upvotes: -1

Related Questions