Marek Buchtela
Marek Buchtela

Reputation: 1003

Define an object with a name constructed using a dynamic value

Okay, I have this piece of code:

int arrPanelsRequired = 4;
string airport;
int arrPanelsMade = 0;
for (; arrPanelsMade <= arrPanelsRequired; arrPanelsMade++)
{
    Panel arrPanelXXX = new Panel();

and I need to replace the XXX with the value of arrPanelsMade. I found several ways to name an object after a variable's value, however, I wasn't able to apply any of them here :(

Upvotes: 1

Views: 89

Answers (4)

Dave Markle
Dave Markle

Reputation: 97671

You have a couple of things going on here that raise red flags. I'll digress from your question just a bit, because I think you're probably going down the wrong road in a couple of respects.

  1. Drop the "arr" prefix, and just call your variables what they are — don't try to emulate Hungarian Notation unless you've got good reason to do so.

  2. Consider using a while loop instead of a for loop if you're not going to perform your initialization in the loop header.

  3. Now on to your question. No, the language doesn't work like that. Use a List<Panel> class instead. That will allow you to add more panels dynamically without having to predefine how many you want, such as in an array.

Upvotes: 1

Honza Brestan
Honza Brestan

Reputation: 10947

I don't think it would be a good idea in general, let alone in C#. I can see many arr prefixes, which leads me to the use of an array. I think you might be looking for something like this:

int arrPanelsRequired = 4;
Panel[] panels = new Panel[arrPanelsRequired];
for (int arrPanelsMade = 0; arrPanelsMade < arrPanelsRequired; arrPanelsMade++)
{
    panels[arrPanelsMade] = new Panel();
}

Upvotes: 2

driis
driis

Reputation: 164281

You should add the panels to a List or array, and access them later by index:

arrPanel = new Panel[arrPanelsRequired];
for( int idx = 0 ; idx < arrPanelsRequired ; idx++)
    arrPanel[idx] = new Panel();

Upvotes: 1

Levi Botelho
Levi Botelho

Reputation: 25204

What you are trying to do is bad practice. It passes in weakly-typed languages, but in strongly-typed languages such as C#, variables need to be explicitly declared. This helps the compiler to catch errors that can be caused by typos or general development mistakes. For example, if you have a variable arrPanel089, how can you/the compiler know if it has been declared? Strong typing can seem like a constraint when coming from weakly-typed languages, but it is really a great tool that saves you a ton of headache as the developer.

If you want to create a set of panels, store them in an array/list/etc and access them by their index. If you want to give them a key, store them in a dictionary which allows you to access values by key instead.

Upvotes: 1

Related Questions