471,627 Members | 1,479 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,627 software developers and data experts.

Reference variable dynamically

Is it possible to reference a variable dynamically? For instance,

string a;

this.controls("a") = "foobar";

Feb 22 '06 #1
11 2585
Hi Roger,
if you want to reference variables like this then you can use reflection.
This allows you to obtain information about types through the metadata
associated with the type. For example, in the code below I set the value of
the name field through reflection by passing the name of the variable:

using System;
using System.Collections;
using System.Text;
using System.Reflection;

namespace ConsoleApplication4
class Program
static void Main(string[] args)
Person p = new Person();

class Person
private string name;

public void SetName(string newName)
BindingFlags.NonPublic | BindingFlags.Instance).SetValue(this, newName);

Hope that helps
Mark Dawson
"Roger" wrote:
Is it possible to reference a variable dynamically? For instance,

string a;

this.controls("a") = "foobar";

Feb 22 '06 #2
> if you want to reference variables like this then you can use reflection.

No, actually, you can't, because local variable names aren't available
via Reflection, in turn because local variables aren't guaranteed to
even exist at run time. They may be optimized away by the compiler.

You can get type information via reflection, but not names of local

However, Roger's original post implied that he wants to find a Control
named "a". That you can do because the Control class has a Name field,
and you can search for the Control with the given Name. Similarly, you
can create classes that "know" their own "keys" and then write other
classes that search for them.

However, there is no (guaranteed-to-always-work) way to inspect code
and find local variable names and manipulate them based on those names.

Feb 23 '06 #3
Mark and Bruce both pointed out the finer issues here. But I think the real
question here is, "what is the goal"? If you could supply more information
about the business logic scenario in which you need to perform this type of
operation, you can probably get more concrete suggestions on a way to get to
"frst base".

Co-founder, Eggheadcafe.com developer portal:

"Roger" wrote:
Is it possible to reference a variable dynamically? For instance,

string a;

this.controls("a") = "foobar";

Feb 23 '06 #4
Actually, what I'd like to achieve is to reference local variables
within a class object. However, I need a method to loop through all
available local string variables and set their values in a case

Feb 23 '06 #5
What Peter is asking is why do you want to do that? What problem are
you trying to solve, such that you decided the best solution was to
reference local variables through some sort of reflection mechanism and
set all of their values?

If we know what the original problem was, maybe there's a different
solution, because there is no way to do it the way you want to do it.

Feb 23 '06 #6
I'm just looking for a solution that will allow me to set variable
values without haveing to explicitly set each variable value. We're
talking about 50 local variables that may or may not need to be set.
On average, only 5-10 variables will be updated on each call.

Feb 24 '06 #7
I'm sorry, but I still don't understand why you don't just explicitly
set each variable value. Somewhere you will have to write code that
determines which variables will be updated for any given call. It seems
to me that that code will be bulkier and harder to maintain than simple
code that just assigns values to variables.

As well, you said that "only 5-10 variables will be updated on each
call." That sounds to me as though you're talking about object
properties or fields, not local variables. One doesn't "update" local
variables on a "call," because they exist only for the lifetime of the
call, so any "updates" will be lost as soon as the method call returns.
If you're talking about instance members, then there ways to do that.

Are you talking about class fields, class properties, or something
else? Could you give a broader description of the problem? Are you
doing bindings to a UI, or updates from a database, or reading data
from some device? I'm still trying to get my head around the original

Feb 24 '06 #8


I think I've got a similar problem. I'm looking to write a generic
logging method for my Web Methods. When an exception occurs I want to
return all the method parameters and their current values, and write
them to a database table.

I can use

System.Reflection.MethodBase.GetCurrentMethod().Ge tParameters()

to get all the parameter names, types, etc in the current method, but
this only provides me with compile time information, i.e. not the
current runtime values of each of the parameters. So what I really need
is some way of getting the value of a variable from having it's name in
the form of a string.


I have the string "userName" and I want to do something like


Is this at all possible, or am I going to have to write a custom method
for each web method?

*** Sent via Developersdex http://www.developersdex.com ***
Mar 8 '06 #9
If they're all the same type, have you considered using a Dictionary
object as a member of your class? Or an ArrayList?

Mar 8 '06 #10
I don't know for sure, but I would attack this in one of two ways.

First, look at what a stack trace can give you back. This is a
different case from what the OP was asking: these are method arguments,
so they must be somewhere on the stack. I wonder if StackTrace can't
get that information for you, since you know the number and types of
your arguments via Reflection?

Or, failing that, I would write some sort of "log my arguments" method,
and do something like this:

public int DoSomeStuff(MyObject obj, int foo, double bar)
Logger.LogMyArguments("DoSomeStuff", obj, foo, bar);

where LogMyArguments has a signature like this:

public static void LogMyArguments(string methodName, params object[]
arguments) { ... }

The information thus collected, together with Reflection data, should
give you everything you need. (In fact, you wouldn't even need
"methodName" in the call above... it's just there in case you forget to
call LogMyArguments somewhere, to help with matching up methods
retrieved via Reflection with their arguments.)

Regardless, I'd try looking at StackTrace first, as it's the cleaner
solution from the client's perspective.

If you find a way to make it work with StackTrace and Reflection,
please post a reply here. Now that I think of it I may find this handy,

Mar 8 '06 #11
Minor correction. You would, in fact, need to do this:

public int DoSomeStuff(MyObject obj, int foo, double bar)
Logger.LogMyArguments("DoSomeStuff", obj, foo, bar);

otherwise the logger won't know when to throw away the relevant

Mar 8 '06 #12

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

134 posts views Thread by James A. Donald | last post: by
3 posts views Thread by Kris Palmer | last post: by
3 posts views Thread by Mike | last post: by
11 posts views Thread by asdf | last post: by
14 posts views Thread by Siegfried Heintze | last post: by
275 posts views Thread by Astley Le Jasper | last post: by
1 post views Thread by XIAOLAOHU | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.