Boolean Parse string

D

davebythesea

Hi folks,

Boolean.Parse("true") returns true, but what if you need to parse something
such as -

Boolean.Parse("(false && false) || (false || (true && true))");

Does something exist in the .NET framework to Parse this kind of string to
one final boolean result?

Thanks for any tips,
David
 
B

Bob Powell [MVP]

The Parse methods for the common value types are there to convert a simple
string to the value. Evaluating expressions is not within its range of
capabilities.

You can write your own expression parser...

--
--
Bob Powell [MVP]
Visual C#, System.Drawing

Ramuseco Limited .NET consulting
http://www.ramuseco.com

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.
 
N

Nicholas Paldino [.NET/C# MVP]

David,

Yes, it's called the compiler. =)

If you really have a need for evaluating these kind of expression
strings, then you could use the CSharpCodeProvider class in the
Microsoft.CSharp namespace, creating the instance and populating it with
code (and with surrounding methods, classes as well, since you will have to
compile an assembly) compiling the code, and then executing it.

Ideally, you would create a class that implements an interface with a
method that returns a result. The body of that method's implementation
would be your expression.

Then, you would compile it all, create an instance of the type you
created/compiled, and then execute the method.

If the expressions is only ever going to be composed of the following
tokens:


(
)
false
true
||
&&

Then I would say it's not so difficult to create your own parser and you
can probably get away with using Expressions or some sort of dynamic code
generation using IL.
 
A

Arne Vajhøj

davebythesea said:
Boolean.Parse("true") returns true, but what if you need to parse something
such as -

Boolean.Parse("(false && false) || (false || (true && true))");

Does something exist in the .NET framework to Parse this kind of string to
one final boolean result?

That is not parsing. That is would be runtime expression evaluation.

It can be done. But it will have some overhead and some security
implications.

Are you sure that you need this ?

(I do have some code snippets if you really need it)

Arne
 
D

davebythesea

Hi folks,

Thanks for all your help. I'm going to have a think about all thats been
said and work out my approach. Once (if) I make some progress I may come back
and ask a couple more questions...

Cheers,
Dave
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top