-1

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?

  • 2
    That string doesn't contain a bool. An example of a string that contains a bool would be "true". What you're asking is how to execute code contained in a string. That's a very different question and one you can research if you use appropriate keywords. – John Sep 19 '22 at 07:24

2 Answers2

1

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?

Connor Stoop
  • 1,574
  • 1
  • 12
  • 26
  • 1
    Yes! I was searching exactly for something like that FLEE, but i couldn't find it! Thank you very much! – Andrea Mangialardo Sep 26 '22 at 13:59
  • Actually, that isn't really true - there is a built-in parser for C# code, but using it involves invoking the Roslyn compiler internals (by adding a reference to `Microsoft.CodeAnalysis.CSharp.SCripting` and calling `CSharpScript.Evaluate...`. – NetMage Mar 13 '23 at 18:00
0

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.");
Dúver Cruz
  • 328
  • 1
  • 12