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

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

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

[{'answer_id': 4633, 'author': 'David Wengier', 'author_id': 489, 'author_profile': 'https://Stackoverflow.com/users/489', 'pm_score': 2, 'selected': False, 'text': '<p>You can use reflection to get the property and invoke it. Something like this:</p>\n\n<pre><code>object result = theObject.GetType().GetProperty("Property" + i).GetValue(theObject, null);\n</code></pre>\n\n<p>That is, assuming the object that has the property is called "theObject" :)</p>\n'}, {'answer_id': 4635, 'author': 'GateKiller', 'author_id': 383, 'author_profile': 'https://Stackoverflow.com/users/383', 'pm_score': 0, 'selected': False, 'text': '<p>You could do it with a prototype function:</p>\n\n<pre><code>void something(int i, string P1) {\n    something(i, P1, String.Empty);\n}\n\nvoid something(int i, string P1, string P2) {\n    something(i, P1, P2, String.Empty);\n}\n\nvoid something(int i, string P1, string P2, string P3) {\n    something(i, P1, P2, P3, String.Empty);\n}\n</code></pre>\n\n<p>and so on...</p>\n'}, {'answer_id': 4636, 'author': 'Karl Seguin', 'author_id': 34, 'author_profile': 'https://Stackoverflow.com/users/34', 'pm_score': 4, 'selected': False, 'text': "<p>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:</p>\n\n<pre><code>protected static void SetField(object o, string fieldName, object value)\n{\n   FieldInfo field = o.GetType().GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);\n   field.SetValue(o, value);\n}\n</code></pre>\n"}, {'answer_id': 4637, 'author': 'Lasse V. Karlsen', 'author_id': 267, 'author_profile': 'https://Stackoverflow.com/users/267', 'pm_score': 7, 'selected': True, 'text': '<p><strong>DISCLAIMER:</strong> This answer was written back in 2008. The landscape has changed drastically since then.</p>\n<p>Look at the other answers on this page, especially the one detailing <code>Microsoft.CodeAnalysis.CSharp.Scripting</code>.</p>\n<p>Rest of answer will be left as it was originally posted but is no longer accurate.</p>\n<hr />\n<p>Unfortunately, C# isn\'t a dynamic language like that.</p>\n<p>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.</p>\n<p>This forum post on MSDN contains an answer with some example code down the page somewhat:<br />\n<a href="https://social.msdn.microsoft.com/Forums/vstudio/en-US/6a783cc4-bb54-4fec-b504-f9b1ed786b54/create-a-anonymous-method-from-a-string" rel="nofollow noreferrer">create a anonymous method from a string? </a></p>\n<p>I would hardly say this is a very good solution, but it is possible anyway.</p>\n<p>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.</p>\n<hr />\n<p><strong>Edit</strong>: Well, that teaches me to read the questions thoroughly first. Yes, reflection would be able to give you some help here.</p>\n<p>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.</p>\n<pre><code>String propName = &quot;Text&quot;;\nPropertyInfo pi = someObject.GetType().GetProperty(propName);\npi.SetValue(someObject, &quot;New Value&quot;, new Object[0]);\n</code></pre>\n<p>Link: <a href="https://learn.microsoft.com/en-us/dotnet/api/system.reflection.propertyinfo.setvalue" rel="nofollow noreferrer">PropertyInfo.SetValue Method</a></p>\n'}, {'answer_id': 4657, 'author': 'MojoFilter', 'author_id': 93, 'author_profile': 'https://Stackoverflow.com/users/93', 'pm_score': 3, 'selected': False, 'text': "<p>All of that would definitely work.  Personally, for that particular problem, I would probably take a little different approach.  Maybe something like this:</p>\n\n<pre><code>class MyClass {\n  public Point point1, point2, point3;\n\n  private Point[] points;\n\n  public MyClass() {\n    //...\n    this.points = new Point[] {point1, point2, point3};\n  }\n\n  public void DoSomethingWith(int i) {\n    Point target = this.points[i+1];\n    // do stuff to target\n  }\n}\n</code></pre>\n\n<p>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.</p>\n\n<p>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.</p>\n"}, {'answer_id': 1564919, 'author': 'Sébastien Ros - MSFT', 'author_id': 142772, 'author_profile': 'https://Stackoverflow.com/users/142772', 'pm_score': 3, 'selected': False, 'text': '<p>I don\'t now if you absolutely want to execute C# statements, but you can already execute Javascript statements in C# 2.0. The open-source library <a href="http://jint.codeplex.com" rel="noreferrer">Jint</a> is able to do it. It\'s a Javascript interpreter for .NET. Pass a Javascript program and it will run inside your application. You can even pass C# object as arguments and do automation on it.</p>\n\n<p>Also if you just want to evaluate expression on your properties, give a try to <a href="http://ncalc.codeplex.com" rel="noreferrer">NCalc</a>.</p>\n'}, {'answer_id': 3841433, 'author': 'Xodem', 'author_id': 464085, 'author_profile': 'https://Stackoverflow.com/users/464085', 'pm_score': 1, 'selected': False, 'text': '<p>You also could implement a Webbrowser, then load a html-file wich contains javascript.</p>\n\n<p>Then u go for the <code>document.InvokeScript</code> Method on this browser. The return Value of the eval function can be catched and converted into everything you need.</p>\n\n<p>I did this in several Projects and it works perfectly.</p>\n\n<p>Hope it helps</p>\n'}, {'answer_id': 6301348, 'author': 'xnaterm', 'author_id': 445334, 'author_profile': 'https://Stackoverflow.com/users/445334', 'pm_score': -1, 'selected': False, 'text': '<p>Unfortunately, C# doesn\'t have any native facilities for doing exactly what you are asking. </p>\n\n<p>However, my C# eval program does allow for evaluating C# code. It provides for evaluating C# code at runtime and supports many C# statements. In fact, this code is usable within any .NET project, however, it is limited to using C# syntax. Have a look at my website, <a href="http://csharp-eval.com" rel="nofollow">http://csharp-eval.com</a>, for additional details.</p>\n'}, {'answer_id': 6457416, 'author': 'Largo', 'author_id': 487303, 'author_profile': 'https://Stackoverflow.com/users/487303', 'pm_score': 4, 'selected': False, 'text': '<p>This is an eval function under c#. I used it to convert anonymous functions (Lambda Expressions) from a string.\nSource: <a href="http://www.codeproject.com/KB/cs/evalcscode.aspx" rel="noreferrer">http://www.codeproject.com/KB/cs/evalcscode.aspx</a></p>\n\n<pre><code>public static object Eval(string sCSCode) {\n\n  CSharpCodeProvider c = new CSharpCodeProvider();\n  ICodeCompiler icc = c.CreateCompiler();\n  CompilerParameters cp = new CompilerParameters();\n\n  cp.ReferencedAssemblies.Add("system.dll");\n  cp.ReferencedAssemblies.Add("system.xml.dll");\n  cp.ReferencedAssemblies.Add("system.data.dll");\n  cp.ReferencedAssemblies.Add("system.windows.forms.dll");\n  cp.ReferencedAssemblies.Add("system.drawing.dll");\n\n  cp.CompilerOptions = "/t:library";\n  cp.GenerateInMemory = true;\n\n  StringBuilder sb = new StringBuilder("");\n  sb.Append("using System;\\n" );\n  sb.Append("using System.Xml;\\n");\n  sb.Append("using System.Data;\\n");\n  sb.Append("using System.Data.SqlClient;\\n");\n  sb.Append("using System.Windows.Forms;\\n");\n  sb.Append("using System.Drawing;\\n");\n\n  sb.Append("namespace CSCodeEvaler{ \\n");\n  sb.Append("public class CSCodeEvaler{ \\n");\n  sb.Append("public object EvalCode(){\\n");\n  sb.Append("return "+sCSCode+"; \\n");\n  sb.Append("} \\n");\n  sb.Append("} \\n");\n  sb.Append("}\\n");\n\n  CompilerResults cr = icc.CompileAssemblyFromSource(cp, sb.ToString());\n  if( cr.Errors.Count &gt; 0 ){\n      MessageBox.Show("ERROR: " + cr.Errors[0].ErrorText, \n         "Error evaluating cs code", MessageBoxButtons.OK, \n         MessageBoxIcon.Error );\n      return null;\n  }\n\n  System.Reflection.Assembly a = cr.CompiledAssembly;\n  object o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler");\n\n  Type t = o.GetType();\n  MethodInfo mi = t.GetMethod("EvalCode");\n\n  object s = mi.Invoke(o, null);\n  return s;\n\n}\n</code></pre>\n'}, {'answer_id': 7204715, 'author': 'roft', 'author_id': 914071, 'author_profile': 'https://Stackoverflow.com/users/914071', 'pm_score': -1, 'selected': False, 'text': '<p>the correct answer is you need to cache all the result to keep the mem0ry usage low.</p>\n\n<p>an example would look like this</p>\n\n<pre><code>TypeOf(Evaluate)\n{\n"1+1":2;\n"1+2":3;\n"1+3":5;\n....\n"2-5":-3;\n"0+0":1\n} \n</code></pre>\n\n<p>and add it to a List</p>\n\n<pre><code>List&lt;string&gt; results = new List&lt;string&gt;();\nfor() results.Add(result);\n</code></pre>\n\n<p>save the id and use it in the code</p>\n\n<p>hope this helps</p>\n'}, {'answer_id': 8020865, 'author': 'Jan Bannister', 'author_id': 460845, 'author_profile': 'https://Stackoverflow.com/users/460845', 'pm_score': 1, 'selected': False, 'text': '<p>Uses reflection to parse and evaluate a data-binding expression against an object at run time. </p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.databinder.eval%28v=vs.71%29.aspx" rel="nofollow">DataBinder.Eval Method</a></p>\n'}, {'answer_id': 14671114, 'author': 'Davide Icardi', 'author_id': 209727, 'author_profile': 'https://Stackoverflow.com/users/209727', 'pm_score': 4, 'selected': False, 'text': '<p>I have written an open source project, <a href="https://github.com/davideicardi/DynamicExpresso/" rel="noreferrer">Dynamic Expresso</a>, that can convert text expression written using a C# syntax into delegates (or expression tree). Expressions are parsed and transformed into <a href="http://msdn.microsoft.com/en-us/library/bb397951.aspx" rel="noreferrer">Expression Trees</a> without using compilation or reflection.</p>\n\n<p>You can write something like:</p>\n\n<pre><code>var interpreter = new Interpreter();\nvar result = interpreter.Eval("8 / 2 + 2");\n</code></pre>\n\n<p>or</p>\n\n<pre><code>var interpreter = new Interpreter()\n                      .SetVariable("service", new ServiceExample());\n\nstring expression = "x &gt; 4 ? service.SomeMethod() : service.AnotherMethod()";\n\nLambda parsedExpression = interpreter.Parse(expression, \n                          new Parameter("x", typeof(int)));\n\nparsedExpression.Invoke(5);\n</code></pre>\n\n<p>My work is based on Scott Gu article <a href="http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx" rel="noreferrer">http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx</a> .</p>\n'}, {'answer_id': 37983894, 'author': 'Eli Arbel', 'author_id': 276083, 'author_profile': 'https://Stackoverflow.com/users/276083', 'pm_score': 6, 'selected': False, 'text': '<p>Using the Roslyn scripting API (more <a href="https://github.com/dotnet/roslyn/wiki/Scripting-API-Samples" rel="noreferrer">samples here</a>):</p>\n\n<pre><code>// add NuGet package \'Microsoft.CodeAnalysis.Scripting\'\nusing Microsoft.CodeAnalysis.CSharp.Scripting;\n\nawait CSharpScript.EvaluateAsync("System.Math.Pow(2, 4)") // returns 16\n</code></pre>\n\n<p>You can also run any piece of code:</p>\n\n<pre><code>var script = await CSharpScript.RunAsync(@"\n                class MyClass\n                { \n                    public void Print() =&gt; System.Console.WriteLine(1);\n                }")\n</code></pre>\n\n<p>And reference the code that was generated in previous runs:</p>\n\n<pre><code>await script.ContinueWithAsync("new MyClass().Print();");\n</code></pre>\n'}, {'answer_id': 45673529, 'author': 'Iucounu', 'author_id': 2346932, 'author_profile': 'https://Stackoverflow.com/users/2346932', 'pm_score': 1, 'selected': False, 'text': '<p>I have written a package, <a href="https://bitbucket.org/jeff_varszegi/sharpbyte-net-public/src/f6bc1e2fc59993ae76e3afc248bee364ba189809/SharpByte.Core/Dynamic/?at=master" rel="nofollow noreferrer">SharpByte.Dynamic</a>, to simplify the task of compiling and executing code dynamically. The code can be invoked on any context object using extension methods as detailed further <a href="https://digitalrumpus.wordpress.com/2017/08/14/easily-execute-dynamic-c-using-extension-methods/" rel="nofollow noreferrer">here</a>. </p>\n\n<p>For example, </p>\n\n<pre><code>someObject.Evaluate&lt;int&gt;("6 / {{{0}}}", 3))\n</code></pre>\n\n<p>returns 3; </p>\n\n<pre><code>someObject.Evaluate("this.ToString()"))\n</code></pre>\n\n<p>returns the context object\'s string representation;</p>\n\n<pre><code>someObject.Execute(@\n"Console.WriteLine(""Hello, world!"");\nConsole.WriteLine(""This demonstrates running a simple script"");\n");\n</code></pre>\n\n<p>runs those statements as a script, etc. </p>\n\n<p>Executables can be gotten easily using a factory method, as seen in the example <a href="https://bitbucket.org/jeff_varszegi/sharpbyte-net-public/src/f6bc1e2fc59993ae76e3afc248bee364ba189809/SharpByte.Core/Dynamic/ObjectExtensions.cs?at=master&amp;fileviewer=file-view-default#ObjectExtensions.cs-396" rel="nofollow noreferrer">here</a>--all you need is the source code and list of any expected named parameters (tokens are embedded using triple-bracket notation, such as {{{0}}}, to avoid collisions with string.Format() as well as Handlebars-like syntaxes):</p>\n\n<pre><code>IExecutable executable = ExecutableFactory.Default.GetExecutable(executableType, sourceCode, parameterNames, addedNamespaces);\n</code></pre>\n\n<p>Each executable object (script or expression) is thread-safe, can be stored and reused, supports logging from within a script, stores timing information and last exception if encountered, etc. There is also a Copy() method compiled on each to allow creating cheap copies, i.e. using an executable object compiled from a script or expression as a template for creating others. </p>\n\n<p>Overhead of executing an already-compiled script or statement is relatively low, at well under a microsecond on modest hardware, and already-compiled scripts and expressions are cached for reuse. </p>\n'}, {'answer_id': 50136420, 'author': 'Ilya Dan', 'author_id': 7379207, 'author_profile': 'https://Stackoverflow.com/users/7379207', 'pm_score': 0, 'selected': False, 'text': "<p>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:</p>\n\n<pre><code>public static object GetPropertyValue(object instance, string memberName)\n{\n    return instance.GetType().GetField(memberName).GetValue(instance);\n}\n</code></pre>\n\n<p>This method will return the value of the member by it's name. It works on regular structure (class).</p>\n"}, {'answer_id': 51322656, 'author': 'Hennadii', 'author_id': 9329578, 'author_profile': 'https://Stackoverflow.com/users/9329578', 'pm_score': 0, 'selected': False, 'text': '<p>You might check the <a href="https://github.com/Heleonix/Heleonix.Reflection" rel="nofollow noreferrer">Heleonix.Reflection</a> 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:</p>\n\n<pre><code>var success = Reflector.Set(instance, null, $"Property{i}", value);\n</code></pre>\n\n<p>Or if number of properties is not endless, you can generate setters and chache them (setters are faster since they are compiled delegates):</p>\n\n<pre><code>var setter = Reflector.CreateSetter&lt;object, object&gt;($"Property{i}", typeof(type which contains "Property"+i));\nsetter(instance, value);\n</code></pre>\n\n<p>Setters can be of type <code>Action&lt;object, object&gt;</code> but instances can be different at runtime, so you can create lists of setters.</p>\n'}]
['https://Stackoverflow.com/questions/4629', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/384/']