Variable variables in C#

midrange

Senior Member
Joined
Apr 8, 2009
Messages
727
Reaction score
0
Is something like this possible in C#? (Maybe my googling skillls are rubbish)

Code:
$required_fields = array('name', 'email', 'message');
			
foreach($required_fields as $field){
				
[B]$$field = $field;[/B]
					
}
 
String[] fields = new String[3] {"name", "email", "message"};
foreach (string s in fields)
{
MessageBox.Show("String array item: " + s);
}
 
That doesn't look to be creating dynamic variables though.

The PHP above creates the variables $name, $email and $message.
 
Why on earth would you want to create variables for which you dont know what their names are at compile time?
 
midrange, you can try a List<>.
Code:
List<string> lst_str_bob= new List<string>();
lst_str_bob.Add("bob1");
etc...

It's in Systems.Collections.Generic
 
Last edited:
Thanks dequadin and UnUnOctium.

Ancalagon, I find "variable variables" pretty handy in PHP.
 
Variable variables are yesterday's news. I use variable variable variables and I can't wait for variable variable variable variables to come out next year.
 
I can't wait for variable variable variable variables to come out next year.

Pffft. All the cool kids are using inconsistent constants.
 

I remember that... was AWESOME! :D

Just a question though, why not just use objects?

Code:
List<object> someList = new List<object> { "test", 1, 2.00, true };
foreach (object o in someList)
{
    Console.WriteLine(o.GetType());
}

A quick test revealed that it BUILDS correctly, but haven't tested the output yet...
 
List<object> someList = new List<object> { "test", 1, 2.00, true };
foreach (object o in someList)
{
Console.WriteLine(o.GetType());
}

That makes the most sense. I suppose the big difference is that PHP doesn't care about variable types.
 
From what I've read (never used it) dynamic is cool.

Has loads of applications for JavaScript & COM.

JavaScript, yes, but for proper enterprise-scale apps where accurate (and strongly-typed) data is of utmost importance, I'm not too sure...

It might be useful in a CMS environment though - even emulating JS scripts on server-side.
 
Variable variables are yesterday's news. I use variable variable variables and I can't wait for variable variable variable variables to come out next year.

Yo dawg, I heard you like variables...
 
Top
Sign up to the MyBroadband newsletter
X