Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

Very simple question.
I need to interpret a string name (extracted from a control name) as an existing array variable name.

Here is the code I simplify to well understand

C#
// My array definition
string[] _dev = { "DC", "192.168.1.1", "Quebec", "Standalone"};

// The string
string str1 = "Server_dev;

// The extraction of the name
string str2 = str1.Substring(str1.Length - 4)     // the result is now the string "_dev"

// Now I need to display the elements '2' of the array _dev :

textBox1.Text = str2.Trim()[2]        // But my _dev array name is not interpreted as requested...


Any idea ?

Thanks a lot

Ben
Posted
Comments
Matt T Heffron 14-Sep-15 17:49pm    
This is pretty odd (but not impossible).
However, if you can describe why you want to do this, what is a bit more of the "big picture", we might be able to provide suggestion(s) of a better way to accomplish what you really intend.
Zoltán Zörgő 15-Sep-15 12:57pm    
Unfortunately, local variables can be enumerated but only as type. You would need to inject a debugger into your code.
Still, I am sure you don't really need this. But without knowing your intentions...

1 solution

You aren't using introspection so this simplified statement will do:

A variable's name is not select-able by another variable's value.

This statement:

C++
textBox1.Text = str2.Trim()[2];


... gives you the character at position 2 which - in this case - is the letter 'e'.

If you were expecting "Quebec", you could do this:

C++
textBox1.Text = _dev[2];
 
Share this answer
 
Comments
Matt T Heffron 14-Sep-15 19:10pm    
You say "A variable's name is not select-able by another variable's value."
That's exactly what he wants to be able to do some way.
That can be done via Reflection, but it isn't pretty.
[no name] 16-Sep-15 12:22pm    
I'm waiting for Ben to clarify what he wants. The first step is for him to understand why his code won't work. Most likely, all he needs is a switch statement, but I'd like to see his response. If Ben is used to using Javascript, he may be expecting something like eval() - which can be done but also a bit of a pain.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900