How to Have an Optional Parameter for an ASP.NET Soap Web Service

Convert string value to operator in C#

I wasn't going to post it, but thought that it might be of some help. Assuming of course that you don't need the advanced generic logic in Jon's post.

public static class Extension
{
public static Boolean Operator(this string logic, int x, int y)
{
switch (logic)
{
case ">": return x > y;
case "<": return x < y;
case "==": return x == y;
default: throw new Exception("invalid logic");
}
}
}

You could use the code like this, with greaterThan being a string with the wanted logic/operator.

if (greaterThan.Operator(a, b))

Convert a string to an operator?

No, not the way you appear to be wanting to. A string literal, by definition, cannot be converted into an operator.

C# Convert string to operator

You cannot convert a string to an "operator". An operator is defined for its operands and it doesn't really make sense to convert a string to an operator if you don't know what your operands are.

Supposing you do know what operands you have, the problem is no longer one of "conversion" per se but actually you are trying to build a parsing engine. This is a problem of considerable difficulty. Unless you actually are trying to create your own scripting language or something of this nature, it is probably just easier to use a lookup table, with each element in the table referring to some method that can be run on the operands.

In C# it is possible to implement such a data structure using a simple switch statement (of course you can make this as fancy as you want ad infinitum but this is the simplest solution).

switch( type )
{
case "+":
return plusOperator(d, c);
case "-":
return minusOperator(d, c);
}

Then you would define suitable methods such as plusOperator and minusOperator to actually implement the logic of your program.

This solution is reasonably dirty in that you are hard-coding certain behaviour but really if you want much more than this in terms of good system architecture it becomes a parsing problem. Should you go down this path the Gang of Four design patterns will make for good reference material (particularly patterns such as the Interpreter, Iterator and Composite)

How could I convert a string variable to a double in C#

You aren't assigning the result of your Convert call to a variable, you're just throwing it away. Convert doesn't alter the type of the existing variable (because, apart from other considerations, you simply can't do that in a strongly-typed language), instead it produces a new variable for you to use in your maths.

The error is, I presume without seeing the relevant code, because you tried to use userAge in your calculations which, as I've just explained, is still a string.

Also, to go back a step, you've never actually assigned the result of the ReadLine operation to the userAge variable in the first place.

This:

Console.WriteLine("What is your age?");
string userAge = Console.ReadLine();
double age = Convert.ToDouble(userAge);

would make more sense. And then use age in your calculations afterwards.

Converting a char (aka: '+') to an operator

First up, this kind of calculator probably suits Stack as the data store.

var theStack = new Stack<decimal>();

Then, if you want to start simple, create a delegate to represent binary operations (eg, operations on the top 2 numbers on the stack)

delegate decimal BinaryOperation(decimal a, decimal b);

You can create methods to implement this;

public decimal AddFn(decimal a, decimal b) 
{
return a+b;
}

then create a dictionary to map between operator names and operator function;

var map = new Dictionary<string, BinaryOperation>();
map.Add("+", AddFn);

Last, use the map when running the program;

foreach(var i in store)
{
decimal number;
BinaryOperation op;

if (decimal.TryParse(i, out number))
{
// we've found a number
theStack.Push(number);
}
else if (map.TryGetValue(i, out op))
{
// we've found a known operator;
var a = theStack.Pop();
var b = theStack.Pop();
var result = op(a,b);
theStack.Push(result);
}
else
{
throw new Exception("syntax error");
}
}

So you can register more operators with the map variable without having to change the core logic of pushing, popping, and operating with values on the stack.

String Convert To Ternary Operator

This should solve it:

static void Main(string[] args)
{
string str = "6 < 5 ? 1002 * 2.5: 6 < 10 ? 1002 * 3.5: 1002 * 4";

Console.WriteLine(EvaluateExpression(str));
Console.ReadKey();
}

public static object EvaluateExpression(string expression)
{
var csc = new CSharpCodeProvider();
var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" });
parameters.GenerateExecutable = false;
CompilerResults results = csc.CompileAssemblyFromSource(new CompilerParameters(new[] { "System.Core.dll" }),
@"using System;

class Program
{
public static object GetExpressionValue()
{
return " + expression + @";
}
}");

if (results.Errors.Count == 0)
{
return results.CompiledAssembly.GetType("Program").GetMethod("GetExpressionValue").Invoke(null, null);
}
else
{
return string.Format("Error while evaluating expression: {0}", string.Join(Environment.NewLine, results.Errors.OfType<CompilerError>()));
}
}

Although I'd suggest something less "brittle", I'm sure there are libraries that can help you.

Answer is based on this.

operators as strings

The way I see it, you have two options - use an expression evaluator or construct, compile
and run C# code on the fly.

I would go with an expression evaluator library, as you do not have to worry about any security issues. That is, you might not be able to use code generation in medium trust environments, such as most shared hosting servers.

Here is an example for generating code to evaluate expressions:
http://www.vbforums.com/showthread.php?t=397264



Related Topics



Leave a reply



Submit