referencing variables PLEASE HELP ME!

  • Thread starter Thread starter name
  • Start date Start date
N

name

Tricky

I'm trying to do the following


string sString = "Here is a test string";
string sFieldRef = "sString";
MessageBox.Show(sFieldRef); //How do I get this line to display: Here is a
test string instead of just sString???
// I am trying to access the
value of sString via sFieldRef


I want the messagebox to show what's stored
in sString (Here is a test string) but by
only using sFieldRef.

I know in Clipper, this is referred to as Macro Expansion.
Not sure how to do this in c#

Thanks in Advance,

Chris
 
Hi,

seems like you need something like a string table, right ?
Just use a Hashtable (or a more memory efficient mapping) to store the
relation between the reference string and the target string.
You do have the query the hashtable everytime to get the target string. No
pain, no gain, of course.
You should also consider using constant integers as the reference. Much
more time and space efficient.

Greetings,

Bram.
 
name said:
Tricky

I'm trying to do the following


string sString = "Here is a test string";
string sFieldRef = "sString";

Uh, how about just assign the sString variable to the sFieldRef variable?
Like:

string sFieldRef = sString;

by using the quotes, you are just assigning a string, "sString", rather than
the value that is stored there.
 
I can't do that because I will be reading from a file the names of fields
ie:

say in my program I have a class that has three variables:
sName,sAddress,sPhoneNumber

I will have a class function that will created a formatted string based on
the order specified by
a text file.

for example, if my program reads from a file that looks like:

file.txt
------------
sAddress
sName
sPhoneNumber



then when I call my output class function, it should display something like
123 First Avenue
Bob Jones
(555) 666-7777

if I change file.txt to look like this:

file.txt
------------
sPhoneNumber
sAddress
sName

then my class output function will display
(555) 666-7777
123 First Avenue
Bob Jones



Thanks,

Chris
 
I would recommend the Hashtable approach specified by Bram first off. However,
you can use reflection to achieve the same goal. If the field is sAddress you
can
use Type.InvokeMember() with the appropriate overloads to get the value.

You can't do macro expansion, because this is macro expansion at run-time, not
macro expansion in the generic sense that is normally done as a precompilation
step.
 
Ah, that makes more sense. I was looking at the code and
it just seemed unusual that the field name was in quotes.
That would have just assigned the string in quotes to that
variable, but I see now how this is supposed to work. Good
suggestion.
 
Back
Top