473,378 Members | 1,688 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 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 2645
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();
p.SetName("bob");
}
}

class Person
{
private string name;

public void SetName(string newName)
{
this.GetType().GetField("name",
BindingFlags.NonPublic | BindingFlags.Instance).SetValue(this, newName);
}
}
}

Hope that helps
Mark Dawson
http://www.markdawson.org
"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
variables.

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
Roger,
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".
Peter

--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com


"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
statement.

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
problem.

Feb 24 '06 #8


Hi,

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.

e.g.

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

GetValue("userName")

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
JDC
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,
too.

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);
...
Logger.PopMyArguments("DoSomeStuff");
}

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

Mar 8 '06 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: johkar | last post by:
This is a bit tricky to describe, but here goes. Any help appreciated. John I declare multiple variables halfway down the page. The number between "mech" and "Num" is generated dynamically in...
134
by: James A. Donald | last post by:
I am contemplating getting into Python, which is used by engineers I admire - google and Bram Cohen, but was horrified to read "no variable or argument declarations are necessary." Surely that...
2
by: Dica | last post by:
i want to allow my "Cut" command to dynamically determine the active control and cut any selected text from it (assuming it's a textBox control). so far i've got this: private void...
3
by: Kris Palmer | last post by:
hi, can somebody explain this problem? it's driving me crazy! i have a requirement to dynamically create a variable quantity of timers with associated start button based on the contents of a...
3
by: Pierre | last post by:
Hello, In an aspx page (mypage.aspx) from a web projet, I would like to get the value of a variable of the projet that is declared as public in a module. The variable can be called from...
3
by: Mike | last post by:
Need some help with passing a label to a subroutine. I have a form with lots of checkboxes. When the form loads i have a procedure that runs to lookup values and check the appropriate boxes. If the...
11
by: asdf | last post by:
C++ allows a reference to a pointer, but doesn't allow a pointer to a reference, why?
14
by: Siegfried Heintze | last post by:
Why does VB.NET V2 force me to pass by value for my set function? When I try to change it to const byref it gives me a syntax error. It seems very inefficient to be passing strings around by value...
275
by: Astley Le Jasper | last post by:
Sorry for the numpty question ... How do you find the reference name of an object? So if i have this bob = modulename.objectname() how do i find that the name is 'bob'
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.