Issue
This Content is from Stack Overflow. Question asked by Andrea Mangialardo
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?
Solution
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?
This Question was asked in StackOverflow by Andrea Mangialardo and Answered by Connor Stoop It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.