Reputation: 11
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
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
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
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
Reputation: 1411
The below one will work
Convert.ToBoolean(true) && Convert.ToBoolean(1==1)
Upvotes: 0
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