-1

Suppose I have this method:

1. public int sum(int a, int b){
2.     int x = 0;
3. 
4.     return x;
5. }

Is it possible to get a string x = a + b; and place in line 3 (during runtime), so that after this string is inserted, the code now does the sum of a and b?

I wanna write some code in a text input field, so when I press a button, all that code (that is a string) should be able to go inside some part of some existing code. The sum above is just an example but it can be anything.

Daniel
  • 7,357
  • 7
  • 32
  • 84
  • do you really need to compile c#? you can do your own parser.if you just want to interpret the code for a "code minigame" for example. –  Oct 27 '19 at 05:41
  • I don't want to create a full parser, I intend to do slight modifications and convert the code to workable C#. – Daniel Oct 27 '19 at 06:03
  • Look, your options are: a) Anu's answer b) Compile text code into a dynamically generated assembly (using CodeDom as mentioned in the accepted answer in the linked question). There isn't really an in between option here. – ProgrammingLlama Oct 27 '19 at 06:07

1 Answers1

1

Instead of inserting string, you could pass a Func<> to the method as parameter. For example,

public int sum(int a, int b,Func<int,int,int> expression = null)
{
   int x = expression == null ? 0 : expression(a,b);
   return x;
}

Now, you could use the method as

var result1 = sum(1,2);  // When you do not want to add the numbers
var result2 = sum(1,2,(a,b)=>a+b); // when you want to add the numbers
Anu Viswan
  • 17,797
  • 2
  • 22
  • 51
  • My question was specific for a reason: the little string `x = a + b;` was just an example, but I wanna have a string that holds a lot of code that that performs lots of actions and put it into a `void` method at runtime. A lambda expression wouldn't fit because I'm expecting the user to write some code and I'll just insert it inside some existing code. – Daniel Oct 27 '19 at 04:50