zzzprojects / Eval-Expression.NET

C# Eval Expression | Evaluate, Compile, and Execute C# code and expression at runtime.
https://eval-expression.net/
Other
449 stars 86 forks source link

TimeSpan and date calculation (may be just a question) #70

Closed egkareem closed 4 years ago

egkareem commented 4 years ago

Hello I am new and I am trying to work out this. I have this code (I am using .NET Fiddle):

  DateTime date1 = new DateTime(2011, 1, 1, 4, 0, 15); 
      DateTime date2 = new DateTime(2010, 1, 1, 4, 0, 15); 
  TimeSpan value = date1.Subtract(date2); 

    //Display the TimeSpan 
    Console.WriteLine("TimeSpan between {0}"+ 
                       " and {1} is {3}", date1,date2,value); 

  string s1="date1.Subtract(date2)";
  Console.WriteLine (s1.Execute<TimeSpan>()); //<-- problem

I get, for the last line the following error message: Run-time exception (line 29): Index (zero based) must be greater than or equal to zero and less than the size of the argument list. Please help or suggest another way.

JonathanMagnan commented 4 years ago

Hello @egkareem .

The first error happen here

Console.WriteLine("TimeSpan between {0}" +
                                  " and {1} is {3}", date1, date2, value);

You currently use '{3}' when there is no argument at this position.

You probably want to do this:

 Console.WriteLine("TimeSpan between {0}" +
                                  " and {1} is {2}", value, date1, date2);

The second error will appears here:

string s1 = "date1.Subtract(date2)";
s1.Execute<TimeSpan>();

The Execute method doesn't know about your local variable date1 and date2, you need to provide it:

string s1 = "date1.Subtract(date2)";
s1.Execute<TimeSpan>(new { date1, date2 });

Let me know if that helped you to get your Fiddle working.

Best Regards,

Jon

egkareem commented 4 years ago

Thank you very much for clearing this out. I am sure it will work, so we can consider this issue close. Special thanks for the quick and detailed response 👍