0

While codeing for a project. i got in a situation where i need to call the method or the member of a type via string expresssion. for example i want to get the result of DateTime.Today value into a result box or a variable..

Is there any way to call the function or a member of a class from the string expression.?

Here are some of the examples what i am looking for.

  1. DateTime.Now

  2. DateTime.Today.ToString("dd-MM-yyyy")

  3. Environment.SpecialFolder.ApplicationData

Above are some of the expression user may pass into a textbox and get the result by invoking them thru any button.

JSJ
  • 5,653
  • 3
  • 25
  • 32

2 Answers2

0

Here you can find an Valid solution with on the fly compiling link here: execute c# code at runtime from code file

this should solve your Problem, but it is not really secure. Depence on the Range of Code execution or "inspection", i would create own commands/rules, to be on the "Save" Side, and prevent the possibility of injecting (evil) Code.

I hope this helps.

Community
  • 1
  • 1
winner_joiner
  • 12,173
  • 4
  • 36
  • 61
0

If the first part of the expression is always the type, you can use reflection to create the type. Something like this, for example:

        string theType = "System.DateTime";
        Type t = Type.GetType(theType);
        Object o = Activator.CreateInstance(t);

But to invoke the method/property, you would have to cast the object to the type, but you don't know the type until runtime, so that will be problematic.

I think you may want to reconsider your approach. Maybe you can give the user an interface where they can choose some options from a list in order to build their expression. For example, let them choose DateTime, Environment, etc. and then based on that selection you give them other options to choose (e.g. Now if they selected DateTime, etc.).

Free form parsing an expression like you're trying to do is going to be difficult and hackish at best.

dcp
  • 54,410
  • 22
  • 144
  • 164