enum or evaluating string as literal
How do I do the following in the shortest code? Not looking for fancy or super creative. Just want to know how to use the basic function(s).
int x=5;
int y=7;
str gthan="y>x"; // how to evaluate gthan as a string to make it return true?
str moreComplex="(y>x || y>10)"; // how to evaluate moreComplex to also return true?
Re: enum or evaluating string as literal
str gthan = (y>x).ToString();
str moreComplex=(y>x || y>10).ToString();
Re: enum or evaluating string as literal
Thanks, but I'm looking for the converse. The return value should be bool true, not str "true"
I want to evaluate the strings gthan and moreComplex as if they were actual C# code without the quotes. How to evaluate in this way? I heard mention of enum from somebody a while back, but don't know if it is correct or how to use it.
Re: enum or evaluating string as literal
then Boolean.Parse((y>x).ToString());
or
bool isTrue = false;
Boolean.TryParse((y>x).ToString(), out isTrue); for safety
Re: enum or evaluating string as literal
That might be the ticket.
Does this syntax do the same?
bool isTrue=Boolean.Parse("y>x");
Re: enum or evaluating string as literal
no. that will fail definitely. What you actually need is the eval() method (like what is in javascript), but C# simply doesn't have it. You can still do that, but have to use CodeDom to use the JScript engine to parse that. Or you can write your own parser to parse that. Either way is complicated.
Re: enum or evaluating string as literal
Thanks. I saw some articles that show how extensive the code is. Of course, once I get it figured out and write it, it will great to have for general use everywhere. I am surprised C# doesn't already have it built in. I used to use a language years back where all you had to do was precede the string with an ampersand:
str exp="y>x";
bool trueOrFalse=&exp;
This, we used to call macro-expansion. Now, they call it runtime evaluation. Whatever they want to call it, it is very useful, and I am surprised it doesn't come stock.
Oh, well. Thanks for chiming in. I'll get it done the hard way.