1

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 :(

Levi Botelho
  • 24,626
  • 5
  • 61
  • 96
Marek Buchtela
  • 973
  • 3
  • 19
  • 42
  • 3
    Why do you need to do that? Sounds like you're actually looking for a list or array. – Ry- Dec 08 '12 at 19:20

4 Answers4

2

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();
}
Honza Brestan
  • 10,637
  • 2
  • 32
  • 43
1

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.

Levi Botelho
  • 24,626
  • 5
  • 61
  • 96
1

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();
driis
  • 161,458
  • 45
  • 265
  • 341
1

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.

Community
  • 1
  • 1
Dave Markle
  • 95,573
  • 20
  • 147
  • 170