tags:

views:

239

answers:

2

What I would like to do is be able to take a Dictionary of key value pairs and make the key the name of a variable and the value the value. From searching the net seems to be very vague on whether this is possible.

The equivalent in PHP would be:

foreach($array as $key=>$val) { $$key = $val; }

Thanks.

A: 

This is doable but it is a slow operation. You'd have to use reflection to access the variables by their string representation.

If at all possible it will be much faster to use Generics to store the objects themselves as the keys. There's an example of that in VB.NET with a Dictionary here. Doing it this way means that there will be no casting or reflection needed at run-time. Plus it allows intellisense to work on the collection directly which is yet another awesome thing about Generics.

Steve Wortham
A: 

You have to declare variables in .Net CLR languages (not to be confused with .Net dynamic runtime languages) at compile time. More than that, it's generally better if you know the types of the variables as well. .Net programmers generally believe that this a good thing (the link is for C#, but the contents still apply).

What do you want to do with these variables? Tell us, and I'll bet we can give you a better way to accomplish the same thing.

Joel Coehoorn
Basically I'm thinking in terms of a silverlight datagrid, it's my understanding that you can't bind an array/list/dictionary ect to a set of columns so I'm thinking rather than having an ugly looking switch which converts each value to a named variable in the code I was thinking it would be better to do it dynamically.
Rob Ryan
I still need to know more about what your grid and the object type in your dictionary look like. Will each column in the grid correspond to a property or field (or transformation from multiple of them) in a record in the dictionary? I haven't used silverlight, but if so I know you could bind that to a winforms or asp.net grid control.
Joel Coehoorn
I went around it, wasn't really a big hassle at all so I won't bother making it more confusing on myself for the sake of slightly cleaner code, thanks for your help.
Rob Ryan