Daniel Camacho
Daniel Camacho

Reputation: 423

Create dynamically attributes name inside a for-loop statement

I would like to create new instances of my Class called "Item" inside a for statement, but I dont know how to give the name dynamically.

for (i=0; i < Counter; i++)
{
    MyClass "XXXX" = Class.method();
}

How can I create 2 strings and give a name? -for instance-

for(i=0;i<2;i++){
  string name + i = "Hello" 
}

EDITED

I ve got some proposals to reach my solution which I can create a Dictionary.

       var bomItems = new Dictionary<Item, Item>();

       for (int i = 0; i < Count; i++)
       {
           Item bomItem = inn.newItem("Part BOM","add");
           bomItems.Add(bomItem + i, bomItem);
       }

But I got a reasonable error in "bomItem + i". that I cannot apply operand '+' . obviously.

Does anyone have any answer for this?

Thank you.

Upvotes: 1

Views: 3890

Answers (4)

Tim Schmelter
Tim Schmelter

Reputation: 460158

You coud use a collection like List<String>:

var list = new List<String>();
for (i=0; i<Counter; i++){
     list.Add("Hello " + i);
}

Edit Accroding to your comment you want to access the variable by it's assigned name. Then you should use a Dictionary instead (if the names are unique).

For example:

var names = new Dictionary<String, String>();
for (i=0; i < Counter; i++){
     names.Add("Name" + i, "Hello");
}

Now you can get the string-value of a given string-key in this way:

String name10 = names["Name10"]; // "Hello" since all values are "Hello" in your sample

Upvotes: 4

Aaron Deming
Aaron Deming

Reputation: 1045

You can use the Dictionary (TKey,TValue) class, where the key is the string you would like to count with.

Dictionary<string, string> myDictionary = new Dictionary<string, string>();
for (i=0; i < Counter; i++)
{
   myDictionary.Add("XXXX", "Hello");  // Matches your above example
}

So XXXX would be your counter string, and Hello would be the string you would like associated with that. Then you can retrieve each string using

string myString = myDictionary[XXXX];

Upvotes: 1

Tigran
Tigran

Reputation: 62256

Another way is use of StringBuilder, like

var builder = new StringBuilder();
for (i=0; i<Counter; i++){
     builder.Append("Hello " + i);
}

and after if you need complete string

builder.ToString().

Much faster then simple string manipulations.

Upvotes: 0

Bala R
Bala R

Reputation: 108957

Use an array!

string[] myArray = new string[Counter];
for (int i = 0; i < Counter; i++){
  myArray[i] = "Hello";
}

Upvotes: 5

Related Questions