omicronlyrae
omicronlyrae

Reputation: 255

Using a variable for a class instance name C#

I've found a few threads on this for other languages but nothing for C#...

Basically, what I need is to instantiate a class with a different name each time (in order to be able to create links between the classes)

My current code:

foreach (DataRow dataRow in RoutingObjects.Rows)
{
    NodeViewModel node = CreateNode(dataRow.ItemArray[1].ToString(), new Point(globalx, globaly), false, dataRow.ItemArray[0].ToString());
}

This creates a new NodeViewModel for every row in the table. What I really need is for each NodeViewModel to have a different name, but I have no idea how to do this.

I tried using a simple int in the loop but I can't add a variable into the class instance name. The (obviously wrong) code is here:

int i = 0;
foreach (DataRow dataRow in RoutingObjects.Rows)
{
    NodeViewModel node+i = CreateNode(dataRow.ItemArray[1].ToString(), new Point(globalx, globaly), false, dataRow.ItemArray[0].ToString());
    i++;
}

I figured by this point that I should be doing things differently and this was probably a terrible idea, but I'd like some advice! If it is possible I'd like to know - otherwise, some alternatives would be very helpful =)

Thanks!

Upvotes: 2

Views: 219

Answers (2)

Timur Lemeshko
Timur Lemeshko

Reputation: 2879

Tim Schmelter right. And, of course, wou can use Linq for more elegant code:

var nodelist = RoutingObjects.Rows.Select(dataRow=>CreateNode(dataRow.ItemArray[1].ToString(), new Point(globalx, globaly), false, dataRow.ItemArray[0].ToString())

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460138

I think you're looking for a collection. You can use a List<NodeViewModel>.

var nodelist = new List<NodeViewModel>();
foreach (DataRow dataRow in RoutingObjects.Rows)
{
    NodeViewModel node = CreateNode(dataRow.ItemArray[1].ToString(), new Point(globalx, globaly), false, dataRow.ItemArray[0].ToString());
    nodelist.Add(node);
}

Now you can access every node in the list via index, for example:

NodeViewModel nvm = nodelist[0];

Upvotes: 7

Related Questions