does c# have an eval method?

  • Thread starter Thread starter Will
  • Start date Start date
W

Will

in javascript or the like, when you wish to evaluate a
string you use eval() for instance if you had five text
boxes named textbox1, textbox2, etc. you would write
something like:

for (x=1;x<5;x++) {
eval(textbox + x).text = "item: " + x;
}


how can you do a similar thing in C#? I cannot believe
that there is no eval method. That would just be
rediculous. Thanks in advance for help! :)


Will
 
No, there is not.

99% of the time you can code around it - and this type of coding is usually
more efficient anyway.
 
No there's no eval method unfortunately but you can use Reflection in most
cases to evaluate property expressions or call expressions on objects
dynamically.

eval(textbox + x).text = "item: " + x;

Here's one of the wrappers I use for this sort of thing:

public const BindingFlags MemberAccess =
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Static | BindingFlags.Instance | BindingFlags.IgnoreCase ;

public static object GetField(object loObject,string lcProperty)
{
return
loObject.GetType().GetField(lcProperty,wwUtils.MemberAccess).GetValue(loObje
ct);
}
public static void SetField(object loObject,string lcProperty,object
loValue)
{

loObject.GetType().GetField(lcProperty,wwUtils.MemberAccess).SetValue(loObje
ct,loValue);
}

You can then call this like so:

(TextBox) tb = wwUtils.GetField(this,"textbox" + x);
string text = tb.Text;

This works as long as the the field or property in question is not marked as
Private as reflection requires external visibility in order to get at the
types. The same sort of thing works for Properties...

Hope this helps,

+++ Rick ---

--

Rick Strahl
West Wind Technologies
http://www.west-wind.com/
http://www.west-wind.com/wwHelp
 
jscript has one, you could always import the approapriate jscript lib and
use that

--
Regards

John Timney (Microsoft ASP.NET MVP)
----------------------------------------------
<shameless_author_plug>
Professional .NET for Java Developers with C#
ISBN:1-861007-91-4
Professional Windows Forms
ISBN: 1861005547
Professional JSP 2nd Edition
ISBN: 1861004958
Professional JSP
ISBN: 1861003625
Beginning JSP Web Development
ISBN: 1861002092
</shameless_author_plug>
 
Back
Top