Click here to Skip to main content
15,887,246 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how can we create a class dynamically in c#? I have tried with below code but I am unable to find where it saves

What I have tried:

C#
static void Main()
    {
        TestExpression("2+1-(3*2)+8/2");
        TestExpression("1*2*3*4*5*6");
        TestExpression("Invalid expression");
    }
    static void TestExpression(string expression)
    {
        try
        {
            int result = EvaluateExpression(expression);
            Console.WriteLine("'" + expression + "' = " + result);
        }
        catch (Exception)
        {
            Console.WriteLine("Expression is invalid: '" + expression + "'");
        }
    }
    public static int EvaluateExpression(string expression)
    {
        string code = string.Format("public static class Func{{ public static int func(){{ return {0};}}}}", expression);
        CompilerResults compilerResults = CompileScript(code);
        if (compilerResults.Errors.HasErrors)
        {
            throw new InvalidOperationException("Expression has a syntax error.");
        }
        Assembly assembly = compilerResults.CompiledAssembly;
        MethodInfo method = assembly.GetType("Func").GetMethod("func");
        return (int)method.Invoke(null, null);
    }

    public static CompilerResults CompileScript(string source)
    {

        CompilerParameters parms = new CompilerParameters();
        parms.GenerateExecutable = false;
        parms.GenerateInMemory = true;
        parms.IncludeDebugInformation = false;
        CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp");
        return compiler.CompileAssemblyFromSource(parms, source);
    }
Posted
Updated 4-Dec-18 5:08am

That codes doesn't save a .cs file anywhere. It creates the text for the code in-memory, compiles it in-memory, and returns the resulting assembly. It doesn't save anything anywhere. Once the assembly is returned, the source code goes out of scope and is destroyed.

So, what's the problem? Though effective, it's a rather inefficient way of evaluating expressions. There are other faster, and more flexible, ways of evaluating expressions if that's what you're trying to do.
 
Share this answer
 
Comments
Member 10318092 4-Dec-18 10:32am    
thanks for your suggestion.
It doesn't save anywhere, the class is created in memory so when your process ends the class is destroyed too.
 
Share this answer
 
Comments
Member 10318092 4-Dec-18 10:33am    
thank you!
As the others have said, there are much better ways to do that. See here for example: A Tiny Expression Evaluator[^]
 
Share this answer
 
Comments
Member 10318092 4-Dec-18 11:22am    
Thanks! I will look the Tiny Expression Evaluator.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900