Does C# has function like eval?

oliver john 1 Reputation point
2021-05-21T06:58:38.12+00:00

Hi, I use C# and vs2019 .net5.0 to program.
When I writing code I found the rewriting is really trouble me. For example,my variable is: var1 var2 var3 var4.
if I want make them equal to 20 I have to write:
var1 = 20;
var2 = 20 ...

But in Matlab there is an function call eval();
it can use string to coding.
like I can write
eval("var"+i+"=20");
it's very convenience!!!
I want to know Can I USE FUNCTION LIKE EVAL in C#?

Thanks a lot for reading my question THANK YOU !!!

Developer technologies C#
{count} votes

2 answers

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,651 Reputation points
    2021-05-21T07:40:54.437+00:00

    Hi oliverjohn-7119,
    The C# doesn't support anything like this directly.
    The closest options are:

    1. Create a full valid C# program and dynamically compile it with CSharpCodeProvider.
    2. Build an expression tree, compile and execute it
      More details I suggest you refer to the following links:
      [C# Eval() support duplicate
      How can I evaluate C# code dynamically?
      eval(string) to C# code
      Is there any function in .Net similar to EVAL of Javascript?
      Best Regards,
      Daniel Zhang

    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Sam of Simple Samples 5,546 Reputation points
    2021-05-21T22:08:10.477+00:00

    If at all possible you should use a collection such as a List for that, as in:

    List<int> vl = new List<int>();
    for (int v = 0; v < 5; ++v)
        vl.Add(20);
    Console.WriteLine("vl[0]={0}", vl[0]);
    

    .Net does however have reflection that could be used for the specific use you ask about. Reflection is costly of machine time so it should be avoided but if you want to make things easier for you then you might like it. You can put var1 through var4 in a class and then use reflection to dynamically get the names as in the following.

    class Program
    {
        static void Main(string[] args)
        {
            classVars d = new classVars();
            Type t = d.GetType();
            foreach (var info in t.GetProperties())
            {
                info.SetValue(d, 20);
            }
            Console.WriteLine("var1={0}", d.var1);
        }
    }
    
    public class classVars
    {
        public int var1 { get; set; }
        public int var2 { get; set; }
        public int var3 { get; set; }
        public int var4 { get; set; }
    }
    

    A fiddle for those is at SetSeriesByReflection.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.