C# variable inside a variable name / C# equivalent of eval()

  • Thread starter Thread starter Matt Jensen
  • Start date Start date
M

Matt Jensen

Howdy
I'm hoping to put a variable inside a variable name.
In JavaScript, you would use eval(myvar+i) or something like that. What is
the C# equiavlent of eval? Or how do I do it in C# .NET?

Here is a very primitive example of what I mean.

for (int i;i<5;i++) {
int eval(myvar+i) = i;
}

Response.Write(myvar1);
Response.Write(myvar2);

Any ideas?
Thanks a lot
Matt
 
Matt said:
I'm hoping to put a variable inside a variable name.
In JavaScript, you would use eval(myvar+i) or something like that. What is
the C# equiavlent of eval? Or how do I do it in C# .NET?

You'd have to use Reflection to access the variable by name. Like this:

class Foo {
int namedField = 42;

void AccessField() {
int val = (int) GetType().InvokeMember("namedField",
BindingFlags.Instance | BindingFlags.NonPublic |
BindingFlags.GetField, null, this, null);

// now you should have 42 in val.
}
}


Oliver Sturm
 

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