Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating objects dynamically in loop

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?

like image 447
user469453 Avatar asked Jun 07 '12 11:06

user469453


3 Answers

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!
like image 127
Michael Buen Avatar answered Oct 19 '22 20:10

Michael Buen


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.

like image 31
Nikhil Agrawal Avatar answered Oct 19 '22 20:10

Nikhil Agrawal


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 ];
}
like image 4
Tim Schmelter Avatar answered Oct 19 '22 21:10

Tim Schmelter