-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.

3
  • 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. Commented Oct 27, 2019 at 5:41
  • I don't want to create a full parser, I intend to do slight modifications and convert the code to workable C#. Commented Oct 27, 2019 at 6: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. Commented Oct 27, 2019 at 6:07

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.