0

I know that I can compile function at runtime and use code copied from this CodeProject article:

   public static MethodInfo CreateFunction(string function)
   {
       string code = @"
           using System;
               
           namespace UserFunctions
           {                
               public class BinaryFunction
               {                
                   public static double Function(double x, double y)
                   {
                       return func_xy;
                   }
               }
           }
       ";
   
       string finalCode = code.Replace("func_xy", function);
   
       CSharpCodeProvider provider = new CSharpCodeProvider();
       CompilerResults results = >provider.CompileAssemblyFromSource(new CompilerParameters(), finalCode);
   
       Type binaryFunction = results.CompiledAssembly.GetType("UserFunctions.BinaryFunction");
       return binaryFunction.GetMethod("Function");
   }

But if I have function in my code,

Func<int, int, int> SomeFunction = (int1, int2)=>
{
    return int1 + int2;
}

how can I use it in generated code so I get something like this:

public static Func<int, int, int> SomeFunction = (int1, int2)=>
{
    return int1 + int2;
}

public static MethodInfo CreateFunction()
{
    string code = @"
        using System;
            
        namespace UserFunctions
        {                
            public class BinaryFunction
            {                
                public static double Function(double x, double y)
                {
                    return SomeFunction(x, y);
                }
            }
        }
    ";

    CSharpCodeProvider provider = new CSharpCodeProvider();
    CompilerResults results = provider.CompileAssemblyFromSource(new CompilerParameters(), code);

    Type binaryFunction = results.CompiledAssembly.GetType("UserFunctions.BinaryFunction");
    return binaryFunction.GetMethod("Function");
}

Update

I managed to do what I wanted with this code

using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public static class Program
    {
        /// <summary>
        /// Главная точка входа для приложения.
        /// </summary>
        [STAThread]
        static void Main()
        {
            var function = CreateFunction();
            var res = function.Invoke(null, new object[] { 1d,2d});
            Console.WriteLine(res);
        }

        public static double SomeFunction(double int1, double int2)
        {
            return int1 + int2;
        }


        public static MethodInfo CreateFunction()
        {
            string code = @"
                    using System;
                    using WindowsFormsApp2;
            
                    namespace UserFunctions
                    {                
                        public class AddFunction
                        {                
                            public static double Function(double x, double y)
                            {
                                return (double)typeof(Program).GetMethod(""SomeFunction"").Invoke(null, new object[] { x, y }); 
                            }
                        }
                    }
                ";

            CSharpCodeProvider provider = new CSharpCodeProvider();

            CompilerParameters options = new CompilerParameters();
            options.GenerateExecutable = false;
            options.GenerateInMemory = true;
            options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
            
            CompilerResults results = provider.CompileAssemblyFromSource(options, code);

            Type binaryFunction = results.CompiledAssembly.GetType("UserFunctions.AddFunction");
            return binaryFunction.GetMethod("Function");
        }
    }
}

Is there better/easier way to do this?

9
  • Can you please clarify how/where you want to "use it in generated code"? Commented Apr 28, 2022 at 17:53
  • 1
    This code has been copied from this CodeProject article. You have the answer there too. Commented Apr 28, 2022 at 17:54
  • @Alexei Levenkov, added some example of what i want to do Commented Apr 28, 2022 at 17:58
  • What is purpose for such string manipulations if C# have LambdaExpression which chan be compiled at runtime? Commented Apr 28, 2022 at 18:32
  • Code you shown as example of what you wanted to do can't compile - so it is not really possible to recommend how to implement it. (Note that there are articles explaining how to add dependencies to dynamically compiled code - make sure to research those if indeed you are looking for something like access to static fields from other classes in run-time compiled code) Commented Apr 28, 2022 at 18:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.