Home > Software engineering >  Convert string containing bool condition to bool (C#)
Convert string containing bool condition to bool (C#)

Time:09-19

I would like to convert (but i think it's not possible) a string into a bool, in this way:

string a = "b.Contains('!')";

private void print(string condition)
{
   string b = "Have a nice day!";

   /* Some kind of conversion here for condition parameter */
   /* like bool.Parse(condition) or Bool.Convert(condition) */

   if(condition)
   {
      Console.Write("String contains !-character.");
   }
}

Mind that the bool-string has to be passed to the function as a parameter.

Is there a way to achieve this?

CodePudding user response:

I think you need to use an auxiliar bool variable, like this example..

 bool aux = false;
    private bool print(string condition)
    {
       string b = "Have a nice day!";
    
       if(b.Contains(condition))
         aux = true;
       return aux;
    }

Or the same example without auxiliar.

 private bool print(string condition)
    {
        string b = "Have a nice day!";
        return b.Contains(condition);
    }

Then call the method print to check if it is true or false and write the message you want

if(print("!"))
   Console.WriteLine("String contains !-character.");

CodePudding user response:

There is no built in way to parse your string to a expression.

But of your goal is to sent the expression to an other function you could do this

using System;

public class Program
{
    public static void Main()
    {       
        print(x=>x.Contains("!"));
    }
    
    private static void print(Func<string,bool> condition)
    {
       string b = "Have a nice day!";

       /* Some kind of conversion here for condition parameter */
       /* like bool.Parse(condition) or Bool.Convert(condition) */

       if(condition.Invoke(b))
       {
          Console.Write("String contains !-character.");
       }
    }
}

if you would like a non build in way you could look at : Is there a tool for parsing a string to create a C# func?

  • Related