How can I evaluate C# code dynamically?

Viewed 77242

I can do an eval("something()"); to execute the code dynamically in JavaScript. Is there a way for me to do the same thing in C#?

An example of what I am trying to do is: I have an integer variable (say i) and I have multiple properties by the names: "Property1", "Property2", "Property3", etc. Now, I want to perform some operations on the " Propertyi " property depending on the value of i.

This is really simple with Javascript. Is there any way to do this with C#?

16 Answers

DISCLAIMER: This answer was written back in 2008. The landscape has changed drastically since then.

Look at the other answers on this page, especially the one detailing Microsoft.CodeAnalysis.CSharp.Scripting.

Rest of answer will be left as it was originally posted but is no longer accurate.


Unfortunately, C# isn't a dynamic language like that.

What you can do, however, is to create a C# source code file, full with class and everything, and run it through the CodeDom provider for C# and compile it into an assembly, and then execute it.

This forum post on MSDN contains an answer with some example code down the page somewhat:
create a anonymous method from a string?

I would hardly say this is a very good solution, but it is possible anyway.

What kind of code are you going to expect in that string? If it is a minor subset of valid code, for instance just math expressions, it might be that other alternatives exists.


Edit: Well, that teaches me to read the questions thoroughly first. Yes, reflection would be able to give you some help here.

If you split the string by the ; first, to get individual properties, you can use the following code to get a PropertyInfo object for a particular property for a class, and then use that object to manipulate a particular object.

String propName = "Text";
PropertyInfo pi = someObject.GetType().GetProperty(propName);
pi.SetValue(someObject, "New Value", new Object[0]);

Link: PropertyInfo.SetValue Method

Not really. You can use reflection to achieve what you want, but it won't be nearly as simple as in Javascript. For example, if you wanted to set the private field of an object to something, you could use this function:

protected static void SetField(object o, string fieldName, object value)
{
   FieldInfo field = o.GetType().GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
   field.SetValue(o, value);
}

All of that would definitely work. Personally, for that particular problem, I would probably take a little different approach. Maybe something like this:

class MyClass {
  public Point point1, point2, point3;

  private Point[] points;

  public MyClass() {
    //...
    this.points = new Point[] {point1, point2, point3};
  }

  public void DoSomethingWith(int i) {
    Point target = this.points[i+1];
    // do stuff to target
  }
}

When using patterns like this, you have to be careful that your data is stored by reference and not by value. In other words, don't do this with primitives. You have to use their big bloated class counterparts.

I realized that's not exactly the question, but the question has been pretty well answered and I thought maybe an alternative approach might help.

You can use reflection to get the property and invoke it. Something like this:

object result = theObject.GetType().GetProperty("Property" + i).GetValue(theObject, null);

That is, assuming the object that has the property is called "theObject" :)

You could do it with a prototype function:

void something(int i, string P1) {
    something(i, P1, String.Empty);
}

void something(int i, string P1, string P2) {
    something(i, P1, P2, String.Empty);
}

void something(int i, string P1, string P2, string P3) {
    something(i, P1, P2, P3, String.Empty);
}

and so on...

I was trying to get a value of a structure (class) member by it's name. The structure was not dynamic. All answers didn't work until I finally got it:

public static object GetPropertyValue(object instance, string memberName)
{
    return instance.GetType().GetField(memberName).GetValue(instance);
}

This method will return the value of the member by it's name. It works on regular structure (class).

You might check the Heleonix.Reflection library. It provides methods to get/set/invoke members dynamically, including nested members, or if a member is clearly defined, you can create a getter/setter (lambda compiled into a delegate) which is faster than reflection:

var success = Reflector.Set(instance, null, $"Property{i}", value);

Or if number of properties is not endless, you can generate setters and chache them (setters are faster since they are compiled delegates):

var setter = Reflector.CreateSetter<object, object>($"Property{i}", typeof(type which contains "Property"+i));
setter(instance, value);

Setters can be of type Action<object, object> but instances can be different at runtime, so you can create lists of setters.

Related