12

I have an array of strings that I am looping through. I would like to loop through the array and on each iteration, create a new object with a name that matches the string value.

For example;

string[] array = new string[] { "one", "two", "three" };

class myClass(){

    public myClass(){
    }
}

foreach (string name in array)
{
   myClass *value of name here* = new myClass(); 
}

Would result in three objects being instantiated, with the names "one", "two" and "three".

Is this possible or is there are better solution?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user469453
  • 349
  • 4
  • 8
  • 17
  • Why do you need to do that? Can you not put the class instances in an array, or perhaps a Dictionary? – Joshua Jun 07 '12 at 11:19

9 Answers9

12

What are you trying to do is not possible in statically-typed language. IIRC, that's possible on PHP, and it's not advisable though.

Use dictionary instead: http://ideone.com/vChWD

using System;
using System.Collections.Generic;

class myClass{

    public string Name { get; set; }
    public myClass(){
    }
}

class MainClass
{

    public static void Main() 
    {
        string[] array = new string[] { "one", "two", "three" };
        IDictionary<string,myClass> col= new Dictionary<string,myClass>();
        foreach (string name in array)
        {
              col[name] = new myClass { Name = "hahah " + name  + "!"};
        }

        foreach(var x in col.Values)
        {
              Console.WriteLine(x.Name);
        }

        Console.WriteLine("Test");
        Console.WriteLine(col["two"].Name);
    }
}

Output:

hahah one!
hahah two!
hahah three!
Test
hahah two!
Michael Buen
  • 38,643
  • 9
  • 94
  • 118
5

While others have given you an alternate but no one is telling why do they recommend you that.

That's because You cannot access object with dynamic names.

(Food for thought: Just think for a moment if you could do so, how will you access them before they are even coded/named.)

Instead create a Dictionary<string, myClass> as others mentioned.

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
4

Use a Dictionary<String, myClass> instead:

var dict= new Dictionary<String, myClass>();

foreach (string name in array)
{
    dict.Add(name, new myClass());
}

Now you can access the myClass instances by your names:

var one = dict["one"];

or in a loop:

foreach (string name in array)
{
    myClass m = dict[ name ];
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

You can use this approach:

  var array = [srt1, srt2, str3];
  var other_array = [];

  for(var i = 0; i <  array.length; i++){
    other_array.push({
    name: array[i]
    })
  }

And for lookup it is easy to find the instance you need by filtering:

var instance1 = other_array.filter(function(result) {
return result.name == 'str1';
});
aabiro
  • 3,842
  • 2
  • 23
  • 36
0

Looks like you need a list of dictionary of your objects:

var myClassDictionary = new Dictionary<string,myClass>();

foreach (string name in array)
{
  myClassDicationry.Add(name, new myClass());
}

// usage:
// myClass["one"] <- an instance of myClass

There are no programming languages that I know of that let you define variable names in runtime.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
0

You could do something like this -

Dictionary<string, myClass> classes = new Dictionary<string, myClass>();

foreach(string name in array)
{
    classes[name] = new myClass();
}

Then you can refer to the named instances later

classes[name].MyClassMethod();
pstrjds
  • 16,840
  • 6
  • 52
  • 61
0

You can use the following code.

string[] array = new string[] { "one", "two", "three" };
Dictionary<String, myClass> list;
class myClass(){

   public myClass(){
   list = new Dictionary<String, myClass>();
   }
 } 

 foreach (string name in array)
 {
    list.Add(name, new myClass())
 }
Asif Mushtaq
  • 13,010
  • 3
  • 33
  • 42
0

You can use lists to store the objects so you can access them

list<myClass> myClasses = new List<myClass>();
foreach (myClass object in myClasses)
{
    //preform interaction with your classes here 
}
Willem T
  • 104
  • 2
  • 12
0

Not applicable to C#, or any statically-typed language for that matter.

For curiosity, I tried if what I remembered in PHP(creating variables on-the-fly) is still correct.

It's still the same PHP, last I used it was year 2000. You can generate variables on-the-fly, not saying it's advisable though, it pollutes the global variables, it can corrupt some existing variable or object with same name.

https://ideone.com/nJDiou

<?php

class MyClass
{
    private $v;
    function __construct($x) {
        $this->v = $x;
    }
    public function getValue() {
        return $this->v;
    }
}

$one = new MyClass("I'm tough!");

echo "The one: " . $one->getValue() . "\n";

$i = 0;
foreach(array("one","two","three") as $h) {
   $$h = new MyClass("Says who? " . ++$i);
}

echo "The one: " . $one->getValue() . "\n";

echo $two->getValue() . "\n";
echo $three->getValue() . "\n";

echo "loop\n";

foreach(array("three","one","two") as $h) {
   echo $$h->getValue() . "\n";
}

?>

Outputs:

The one: I'm tough!
The one: Says who? 1
Says who? 2
Says who? 3
loop
Says who? 3
Says who? 1
Says who? 2
Michael Buen
  • 38,643
  • 9
  • 94
  • 118