Kinggadino
Kinggadino

Reputation: 47

Creating a variable name by using a string

I am creating a kind of interface builder for windows using C# and XAML and was wondering if it was possible to create a variable name out of a string (Label label_string = "Something";). For example, every time a new label is created the variable will be named {label1, label2, label3, ...}. I'm thinking of just creating an array of labels and changing the Name property of each one but I would like to know if my other thought was possible.

Upvotes: 0

Views: 143

Answers (1)

CodingGorilla
CodingGorilla

Reputation: 19842

The short answer is no. If you want to stick with the CLR and strongly typed objects then those objects are defined at compile time and their definition cannot be changed after that.

Now if you want to get more complicated, there are ways to do this using reflection, and emitting new IL/Wrapper classes, and stuff like that. There's also the DLR, where you can use dynamic objects (ala Javascript) in which the definition of the object is defined at run time rather than compile time. But for what you want to do this is probably way more complex and inefficient than just maintaining an array of Label controls where you change the Name property as you described.

UPDATE

It's out of the scope of a SO answer to try and explain how you could actually do this as it's very complicated. But there are several approaches you could research if you are interested.

One of them would be to actually generate c# code and run it through the compiler at run time and then dynamically load that assembly. A quick Bing! search turned up this link that describes doing something like that: http://support.microsoft.com/kb/304655

Another approach would be to use the System.Reflection.Emit namespace to emit CIL instructions in order to build an in memory assembly. Again, a quick Bing! search turned up this link which talks about this kind of thing: http://msdn.microsoft.com/en-us/library/3y322t50(v=vs.110).aspx

Note: the above links aren't exact explanations on how to what you're asking, but they give you an idea about the approach and you will need to do much more research to figure out how to fit it to your specific scenario.

Upvotes: 1

Related Questions