How to evaluate in C# a string of expression

  • Thread starter Thread starter Bhuvanesh
  • Start date Start date
B

Bhuvanesh

Hi
Happy 2006

Anyone please suggest me how to evaluate a string of expression.
I have used the same in VBscript and javascript.
e.g.

stringvariable1 = "TemplateTopUserControl";
stringvariable2 = "\"TemplateTop.ascx\"";

"this." + stringvariable1 + " = (" + stringvariable1 + ")this.LoadControl("
+ stringvariable2 +")"

I want this to be executed as

this.TemplateTopUserControl = (TemplateTopUserControl)
this.LoadControl("TemplateTop.ascx");

I know that we can use eval function available in javascript so I want to
know the equivalent in C#.


Thanks very much

BG
 
The only way I know of is via reflection; you'd do something like:

object value = this.LoadControl(stringVariable2);
this.GetType().GetProperty(stringvariable1).SetValue(this, value, null);


If you needed the "LoadControl" to be dynamic, you'd use GetMethod on the
type.

Note you don't need the cast here; the runtime will check that "value" is
appropriate for the property.

Hope this helps,

Marc
 
Bhuvanesh said:
Hi
Happy 2006

Anyone please suggest me how to evaluate a string of expression.
I have used the same in VBscript and javascript.
e.g.

stringvariable1 = "TemplateTopUserControl";
stringvariable2 = "\"TemplateTop.ascx\"";

"this." + stringvariable1 + " = (" + stringvariable1 + ")this.LoadControl("
+ stringvariable2 +")"

I want this to be executed as

this.TemplateTopUserControl = (TemplateTopUserControl)
this.LoadControl("TemplateTop.ascx");

I know that we can use eval function available in javascript so I want to
know the equivalent in C#.


Thanks very much

BG
Depends on what you want to do. If you want to provide something similar
like scripting capabilities to you app, you can compile your code on the
fly into an in memory assembly and execute it.

If you want to configure your application, I would model the abstraction
of what you want to do (e.g. loading a control) into a interface and
exchange the implementation, e.g via the config file.

HTH,
Andy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top