1

Is there a way to execute a string as C# code in ASP.NET 5 with Roslyn?

In my case I want to dynamically convert a string to an linq expression.

For example:

obj.SomeFunc( "x => x.Username".ToLinqExpression() );

Or something like:

Eval("obj.SomeFunc(x => x.Username); ");

Is this possible in ASP.NET 5?

1
  • Look at the expression tree or dynamic linq. Commented Dec 22, 2015 at 20:37

3 Answers 3

2

You can do something like this using Roslyn Scripting. For example:

public class Globals
{
    public ObjType obj;
}

…

CSharpScript.EvaluateAsync(
    "obj.SomeFunc(x => x.Username)", globals: new Globals { obj = obj });
Sign up to request clarification or add additional context in comments.

Comments

0

As already suggested, you can try Dynamic Linq. I have used to generate sorting based on dynamic properties and it seems to work very well.

Comments

0

Evaluating a string requires compilation and an expression tree can easily be built using the Expression Class and compiling a delegate.
Expression class is in System namespace.

Here are a couple of ways:

static Func<int, int, int, int, int> delInt = (i, j, k, l) => i + j * k - l;
int rslt1 = delInt(2, 3, 4, 5);  // evaluates lambda and returns int
static Func<int> delInt1 = () => 2 + 3 * 4 - 5;  // type the expression after => instead of assigning it to a string.
int rslt2 = delInt1();   // takes no parameters and returns int result.

Comments

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.