Convert string containing bool condition to bool (C#) - c#

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?

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?

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.");

Related

swift static extension like c#

Hi is there any change to write static extension in Swift like is in C#? I mean in C# i can write same thing like this:
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
and call it like this:
var s = ""; var x = s.WordCount();
I know i can do same thing in swift, but it work only on class types. On static types I must write something like :
var str:String?
let s = String.IsNilOrEmpty(str)
for this extension:
extension String {
static func isNilOrEmpty(str: String?) -> Bool{
if str == nil {
return true
}
if str!.isEmpty{
return true
}
return false
}
}
Is there change to call it like this:
let s = str.IsNilOrEmpty()
Thanks for help or kicking out to right way.
You can define functions with the same name, one static, one not static.
extension String {
static func myfunc() -> String {
return "static"
}
func myfunc() -> String {
return "func"
}
}
let s3 = ""
print(s3.myfunc()) // output = "func"
print(String.myfunc()) // output = "static"
In this case, if 'someOptionalString' is nil, then it will not call the function.
let some = someOptionalString.IsNilOrEmpty()

How to cascade optional parameter?

I have a worker method with an optional parameter
Work(string input = DefaultInput)
{
//do stuff
}
And I have a wrapper around this, which also take the string input, but this can also be optional...
WorkWrapper(int someParameter, string input = DefaultInput)
{
//do initialization
Work(input);
}
The problem here is I duplicate reference to DefaultInput, if, say, I change the default input of work to NewDefaultInput, I will need to update the workWrapper as well, otherwise it will still use the old default.
Is there a way so that the default input do not need to be declared twice? Possibly without having two overloads for workwrapper..
If you want the defaults to be in sync between the two methods, you really don't need the default in the wrapper, right?
public void Work(string input = DefaultInput)
{
//do stuff
}
…
public void WorkWrapper(int someParameter, string inputOverride = null)
{
//do initialization
if (inputOverride == null) Work();
else Work(inputOverride);
}
If they are in the same class/hierarchy, you could also just declare a const to ensure that the defaults remain the same.
private const string DEFAULT_INPUT = "Default Input"; // protected if in base class
public void Work(string input = DEFAULT_INPUT)
{
//do stuff
}
public void WorkWrapper(int someParameter, string input = DEFAULT_INPUT)
{
//do initialization
Work(input);
}

expected class, delegate, enum, interface or struct error C#

have a php code like this,going to convert it in to C#.
function isValid($n){
if (preg_match("/\d+/",$n) > 0 && $n<1000) {
return true;
}
return false;
}
Here is my try,BUT error shown Error is "expected class, delegate, enum, interface or struct error C#"
public string IsValidate(string Item)
{
string Result = Item;
try
{
Result = System.Text.RegularExpressions.Regex.Replace(InputTxt, #"(\\)([\000\010\011\012\015\032\042\047\134\140])", "$2");
}
catch(Exception ex)
{
console.WriteLine(ex.Message)
}
return Result;
}
What is the error,Is there any other way to implement this better than my try ?
i got this snippet from here code
You haven't define this method inside a class/struct that is why you are getting this error. You may define this method inside a class.
public class MyValidator
{
public string IsValidate(string Item)
{
//Your code here
}
}
Later you can use it like:
MyValidator validator = new MyValidator();
validator.IsValid("Your string");
Also you are missing semicolon at the end of the Console.Write statement, plus 'c' for Console should be in uppercase
Edit:
Since in your php code, it looks like you are trying to see if the string passed is an integer and it is less than 1000, you may use the int.TryParse like the following:
public class MyValidator
{
public bool IsValidate(string Item)
{
string Result = Item;
int val;
if (int.TryParse(Item, out val) && val > 0 && val < 1000)
{
return true;
}
else
{
return false;
}
}
}
In you main method you can do:
static void Main()
{
MyValidator validator = new MyValidator();
Console.WriteLine(validator.IsValidate("asdf123")); // This will print false
Console.WriteLine(validator.IsValidate("999")); //This will print true
Console.WriteLine(validator.IsValidate("1001")); //This will print false
}
In C# a method must be placed inside a class or struct:
public class Validator {
public string IsValidate(string item) {
...
}
}
In this case I would probably translate it like this:
public static class Validator {
public static bool IsValid(string item) {
int value;
return int.TryParse(item, out value)
&& value > 0 && value < 1000;
}
}
You could define your function inside a static class such that you dont have to create an instance of it before invoking the function. Like,
public static class Validator
{
public static string IsValidate(string item)
{
// ...
}
}
Then, you can call it using:
Validator.IsValidate("String to validate")
EDIT: You could then check that your function is returning what you expect by doing:
if(Validator.IsValidate("String to validate") == "Expected result")
{
/* Logic to be executed here */
}

How to pass method result as parameter to base class constructor in C#?

I've trying to achieve something like this:
class App {
static void Main(string[] args) {
System.Console.WriteLine(new Test("abc")); //output: 'abc'
System.Console.ReadLine();
}
}
I can do this passing by an variable:
class Test {
public static string str;
public Test (string input) { str = input; }
public override string ToString() {
return str;
}
}
works fine.
But, my desire is do something as:
class Test {
public static string input;
public Test (out input) { }
public override string ToString() {
return input;
}
}
System.Console.WriteLine(new Test("abc test")); //abc test
Don't works.
How I do this?
Thanks,advanced.
You can't. The variable approach is exactly the correct way, although the variable shouldn't be declared static, and shouldn't be a public field.
class Test {
public string Input {get;set;}
public Test (string input) { Input = input; }
public override string ToString() {
return Input;
}
}
I have an impression that you're not entirely understand what out keyword means. Essentially when you're writing something like void MyMethod(out string var) it means you want to return some value from method, not pass it into method.
For example there's bool Int32.TryParse(string s, out int result). It parses string s, returns if parse was successful and places parsed number to result. Thus, to correctly use out you should have real variable at the calling place. So you can't write Int32.Parse("10", 0) because this method can't assign result of 10 to 0. It needs real variable, like that:
int result;
bool success = Int32.TryParse("10", out result);
So, your desire is somewhat else - it is not in line with language designer's intentions for out :)

Can I conditionally control method calls at runtime with attributes?

The Conditional Attribute in .NET allows you to disable the invocation of methods at compile time. I am looking for basically the same exact thing, but at run time. I feel like something like this should exist in AOP frameworks, but I don't know the name so I am having trouble figuring out if it is supported.
So as an example I'd like to do something like this
[RuntimeConditional("Bob")]
public static void M() {
Console.WriteLine("Executed Class1.M");
}
//.....
//Determines if a method should execute.
public bool RuntimeConditional(string[] conditions) {
bool shouldExecute = conditions[0] == "Bob";
return shouldExecute;
}
So where ever in code there is a call to the M method, it would first call RuntimeConditional and pass in Bob to determine if M should be executed.
You can actually use PostSharp to do what you want.
Here's a simple example you can use:
[Serializable]
public class RuntimeConditional : OnMethodInvocationAspect
{
private string[] _conditions;
public RuntimeConditional(params string[] conditions)
{
_conditions = conditions;
}
public override void OnInvocation(MethodInvocationEventArgs eventArgs)
{
if (_conditions[0] == "Bob") // do whatever check you want here
{
eventArgs.Proceed();
}
}
}
Or, since you're just looking at "before" the method executes, you can use the OnMethodBoundaryAspect:
[Serializable]
public class RuntimeConditional : OnMethodBoundaryAspect
{
private string[] _conditions;
public RuntimeConditional(params string[] conditions)
{
_conditions = conditions;
}
public override void OnEntry(MethodExecutionEventArgs eventArgs)
{
if (_conditions[0] != "Bob")
{
eventArgs.FlowBehavior = FlowBehavior.Return; // return immediately without executing
}
}
}
If your methods have return values, you can deal with them too. eventArgs has a returnValue property that is settable.
I believe this would be a very simple way of doing what you described:
public static void M()
{
if (RuntimeConditional("Bob"))
{
Console.WriteLine("Executed Class1.M");
}
}
Thanks

Categories

Resources