1

This is an extension of this question: Is it possible to dynamically compile and execute C# code fragments?

But is it possible to reference fields, properties and methods of a certain object? For example:

public class SomeClass
{
    public int a, b;

    public int SomeMethod(int a, int b, int c)
    {
        return a + b + c;
    }

    public void Execute()
    {
        int c = 3;
        string code = "a = b = 2; int result = SomeMethod(a, b, c);";
        // Compile and execute code here
    }
}

The code obviously makes no sense in terms of functionality, but it's just an example.

Martin
  • 131
  • 2
  • 8
  • I think you'll find what you want in here https://stackoverflow.com/questions/355062/is-there-a-string-math-evaluator-in-net – Johni Michels Aug 19 '18 at 20:17
  • No, he is asking for a math evaluator. – Martin Aug 19 '18 at 20:53
  • This: https://josephwoodward.co.uk/2016/12/in-memory-c-sharp-compilation-using-roslyn and this: http://www.tugberkugurlu.com/archive/compiling-c-sharp-code-into-memory-and-executing-it-with-roslyn will give you comprehensive starting point. Your keywords for search are "roslyn compile string". Roslyin is a C# compiler and it is available as a NuGet for consumption. – trailmax Aug 19 '18 at 22:58

2 Answers2

0

I wouldn't know a way, but you can call string tmp = Path.GetTempFile() to create a temp file and do a code = "void Main(string[] args){int a = b = 2; int result = SomeMethod(a, b, c); File.WriteAllBytes(\"" + tmp + "\", BitConverter.GetBytes(result));" to save the result. Then you can load it with BitConverter.ToInt32(File.ReadAllBytes(tmp)).

chrissx
  • 13
  • 1
  • 5
0

I think you're looking for something like Lambda Expression Serializers DynamicExpresso

Kimboo
  • 42
  • 2