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?

DrWh0
  • 126
  • 7
  • Can you please clarify how/where you want to "use it in generated code"? – Alexei Levenkov Apr 28 '22 at 17:53
  • 1
    This code has been copied from this [CodeProject article](https://www.codeproject.com/tips/715891/compiling-csharp-code-at-runtime). You have the answer there too. – McNets Apr 28 '22 at 17:54
  • @Alexei Levenkov, added some example of what i want to do – DrWh0 Apr 28 '22 at 17:58
  • What is purpose for such string manipulations if C# have `LambdaExpression` which chan be compiled at runtime? – Svyatoslav Danyliv Apr 28 '22 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) – Alexei Levenkov Apr 28 '22 at 18:32
  • What is the purpose of `finalCode` since `func_xy` does not exist in it and `function` is never defined? – NetMage Apr 28 '22 at 18:39
  • @NetMage, I just forgot to delete this line – DrWh0 Apr 28 '22 at 18:53
  • @AlexeiLevenkov, I managed to do what I whanted and added this to the question. Is there better way to do this? – DrWh0 Apr 28 '22 at 19:34
  • @DrWh0, if it is working for you create answer, not just update question. – Svyatoslav Danyliv Apr 29 '22 at 07:50

0 Answers0