Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
1.60/5 (2 votes)
See more:
Hi,
Is there is any way for converting a statement in string to Boolean value. Please see below (Like this).
C#
string CndtnStmnt = "(Textbox1.text == \"god\" )";
if (Convert.ToBoolean(CndtnStmnt))
{
    //Do Something
}

Thanks in Advance.
Posted
Comments
Sergey Alexandrovich Kryukov 22-Oct-14 0:37am    
Why?
—SA
George Jonsson 22-Oct-14 0:48am    
Maybe if you explain what you really want to do, you can get an answer.
What you try to do looks strange.
Manu Prasad 22-Oct-14 0:50am    
http://www.c-sharpcorner.com/UploadFile/mgold/CodeDomCalculator08082005003253AM/CodeDomCalculator.aspx
Like this I need to evaluate an expression while executing the application.
Manu Prasad 22-Oct-14 1:00am    
please see below.I have a gridview like this..

|(/)|Name | Prop.| Condition | Value | (/)|And/or|

| ( | Part | Name | Equals | Test | ) |And |
| ( | Part | Class| Not Equals| 123 | ) | |

I can convert the above things to a expression like
"(Part.Name == "Test" )&& (Part.Class != 123 ).But I need to execute the statement..

Hi Manu Prasad,

I have prepared one method which can take the expression statement to execute as parameter and give the boolean result as you are expecting.

You need the namespaces as listed below :-
C#
using System;
using System.Text;
using System.CodeDom;
using Microsoft.CSharp;
using System.Reflection;
using System.Windows.Forms;
using System.CodeDom.Compiler;
using System.Collections.Generic;


I hope the below method will be helpful for you which created exclusively for your post.

C#
public bool TestDymanicCode(string strCodeSnippetToExecute)
        {
            bool bResult = false;
            string strSourceTemplate =
            @"using System; 
                      using System.Windows.Forms; 

                      namespace TestNamespace { 
                         public static class TestClass { 
                           public static bool Execute() {
                             @Placeholder
                           }
                         }
                       }";
            string strReplacedCode = strSourceTemplate.Replace("@Placeholder", strCodeSnippetToExecute);
            CodeSnippetCompileUnit objCodeSnippetCompileUnit = new CodeSnippetCompileUnit(strReplacedCode);

            using (CSharpCodeProvider provider =
                new CSharpCodeProvider(new Dictionary<string,> { { "CompilerVersion", "v3.5" } }))
            {
                CompilerParameters objCompilerParameters = new CompilerParameters();
                objCompilerParameters.ReferencedAssemblies.Add("System.dll");
                objCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
                objCompilerParameters.GenerateExecutable = false;
                objCompilerParameters.GenerateInMemory = true;
                objCompilerParameters.IncludeDebugInformation = false;

                CompilerResults objCompilerResults = provider.CompileAssemblyFromDom(objCompilerParameters, objCodeSnippetCompileUnit);

                if (!objCompilerResults.Errors.HasErrors)
                {
                    Type type = objCompilerResults.CompiledAssembly.GetType("TestNamespace.TestClass");
                    MethodInfo method = type.GetMethod("Execute");

                    /* YOU CAN GET YOUR BOOLEAN RESULT HERE. */
                    object val = method.Invoke(null, new object[] { });
                    bResult = Convert.ToBoolean(val);
                }
                else
                {
                    StringBuilder objSB = new StringBuilder();
                    foreach (CompilerError objCompilerError in objCompilerResults.Errors)
                        objSB.AppendFormat("Error found in line {0}:\n\n{1}", objCompilerError.Line, objCompilerError.ErrorText);
                    MessageBox.Show(objSB.ToString(), "Compiler Error");
                }
            }
            return bResult;
        }


The upper method can be called like this :-
C#
string strReturnCodeSnippet = "return (\"" + txtTestDynamic.Text + "\" == \"Test\");";
            MessageBox.Show(TestDymanicCode(strReturnCodeSnippet).ToString());


Hope you will be helpful by this.
 
Share this answer
 
Comments
Manu Prasad 22-Oct-14 4:34am    
Thank you!!!..Its Working...!!
If you want to try and create the equivalent of the general-purpose 'Eval command in VB.NET, you are taking on a lot of work. Using CodeDom, building Expression Trees, etc. is tricky.

CodeProject member Jing Lu, author of ReoGrid, has published a very robust scripting language for C# that you could use: [^].

On this Google search page you will find links to several CodeProject articles showing various techniques for string=>execute-code in C# including the idea of using VB.NET's Eval in C#: [^].
 
Share this answer
 
No, or at least not easily.
Because the code you show references controls and properties on the form itself, you would need to compile the line you are trying to evaluate and execute it directly as part of your code.

This is possible - very, very nasty, but possible - but there is probably a much less expensive and complex way to do what you are trying to achieve than something like this.
I'd look for that instead if I was you!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900