0

I have a string. For example

 string str="if(a>b) {return a;} else {return b;}"

I want to evaluate or make function, say func(int a, int b) which will have the code of 'str'.

Tharif
  • 13,794
  • 9
  • 55
  • 77
  • 3
    The example you have given, is that the simplest possible scenario or the most complicated scenario? If it's the former then you might as well send an email to Microsoft asking them to share their compiler code with you :). Writing a parser/compiler is no easy task, I don't generally ask "why" but why are you looking at implementing this functionality? :) – Ruskin Jun 20 '15 at 04:22
  • possible duplicate of [Is it possible to compile and execute new code at runtime in .NET?](http://stackoverflow.com/questions/234217/is-it-possible-to-compile-and-execute-new-code-at-runtime-in-net) – Dan Getz Jun 20 '15 at 04:38
  • @Ruskin...I am asking this because i want to use 'if else' entered by user as a function to the program itself. – sabhrish balasubramanian Jun 20 '15 at 08:29

2 Answers2

1

you may need to use CSharpCodeProvider as in this answer

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

class Program
{
    static void Main(string[] args)
    {
        var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
        var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
        parameters.GenerateExecutable = true;
        CompilerResults results = csc.CompileAssemblyFromSource(parameters,
        @"using System.Linq;
            class Program {
              public static void Main(string[] args) {
                var q = from i in Enumerable.Range(1,100)
                          where i % 2 == 0
                          select i;
              }
            }");
        results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
    }
}
Community
  • 1
  • 1
farid bekran
  • 2,684
  • 2
  • 16
  • 29
1

In general, this is not an easy thing to do, but the System.CodeDom namespace is where your journey will start.

Look at the following CodeProject article on the matter as a start: http://www.codeproject.com/Articles/26312/Dynamic-Code-Integration-with-CodeDom

The basics of it is as follows (as taken from the codeproject article):

private static Assembly CompileSource( string sourceCode )
{
   CodeDomProvider cpd = new CSharpCodeProvider();
   CompilerParameters cp = new CompilerParameters();
   cp.ReferencedAssemblies.Add("System.dll");
   //cp.ReferencedAssemblies.Add("ClassLibrary1.dll");
   cp.GenerateExecutable = false;
   // Invoke compilation.
   CompilerResults cr = cpd.CompileAssemblyFromSource(cp, sourceCode);

   return cr.CompiledAssembly;
}

The resultant assembly will have the class/method/code you are interested in, and then you can use reflection to call your method. Since your example just uses a code fragment, you will probably have to wrap it in a class/method before passing it to this method.

I hope that helps, but dynamic code generation in C# is not easy and this is just a start.

syazdani
  • 4,760
  • 1
  • 26
  • 35
  • I get the message, An unhandled exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll Additional information: Could not load file or assembly 'file:///C:\Users\Sabhrish\AppData\Local\Temp\5diuzimc.dll' or one of its dependencies. The system cannot find the file specified. – sabhrish balasubramanian Jun 20 '15 at 07:56