Bob M wrote:
For your convenience I post example code as Console Application:
using System;
class ProgramConsole {
private const string StrGivenFn = "Math.Pow(x, 3) + (3 * Math.Pow(x, 2)) -
(10 * x)";
public static double givenFn(double x) {
return (Math.Pow(x, 3) + (3 * Math.Pow(x, 2)) - (10 * x));
// The expression following return statement is
// same as the constant StrGivenFn. How can StrGivenFn be used?
}
static void Main(string[] args) {
Console.WriteLine("f(x) = " + StrGivenFn);
Console.WriteLine("f(x) = " + givenFn(6) + " at x=6");
Console.ReadLine();
}
}
You want to evaluate a C# expression at runtime ?
You can call the compiler.
Below are some code to get you started.
Arne
================================================== ============
using System;
using System.Collections.Generic;
using System.Reflection;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
namespace E
{
public class DynComp
{
private static int n = 0;
private static Dictionary<string,objectm = new
Dictionary<string,object>();
public static double Eval(string expr, double x)
{
object o;
if(m.ContainsKey(expr))
{
o = m[expr];
}
else
{
n++;
string cn = "c" + n;
string src = "using System; public class " + cn + " { public static
double Eval(double x) { return " + expr + "; } }";
CodeDomProvider comp = new CSharpCodeProvider();
CompilerParameters param = new CompilerParameters();
param.GenerateInMemory = true;
param.ReferencedAssemblies.Add("System.dll");
CompilerResults res = comp.CompileAssemblyFromSource(param,
src);
Assembly asm = res.CompiledAssembly;
o = asm.CreateInstance(cn);
m.Add(expr, o);
}
return (double)o.GetType().InvokeMember("Eval",
BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Static |
BindingFlags.InvokeMethod, null, null, new object[] { x });
}
}
public class MainClass
{
private const string StrGivenFn = "Math.Pow(x, 3) + (3 * Math.Pow(x,
2)) - (10 * x)";
public static double GivenFn(double x) {
return (Math.Pow(x, 3) + (3 * Math.Pow(x, 2)) - (10 * x));
}
public static void Main(string[] args)
{
Console.WriteLine(GivenFn(6));
Console.WriteLine(DynComp.Eval("Math.Pow(x, 3) + (3 * Math.Pow(x, 2))
- (10 * x)", 6));
Console.ReadLine();
}
}
}