Techadox
Techadox

Reputation: 35

Is it possible to include the initializer from for loop in the name of a variable that will be declared inside it?

static void Main(string[] args)
{
    for (int i = 0; i < int.MaxValue; i++)
    {
        client client[i] = new client();
    }
}

I need to make the loop add an automated variable that gets declared with every loop. The variable would be called client1 then client2 etc. Or is there a better way to loop methods?

Upvotes: 0

Views: 72

Answers (2)

Melnikov Sergei
Melnikov Sergei

Reputation: 114

If you really need the access to all your variables, @HimBromBeere is right. But if you, for example, have static field in the Client class and only need current variable, you can do something like:

while(true) { var c = new Client(); }

In this case you can check your current state. For example: c.Name; will give you information about the client, which is processed at the current iteration. It will work, if you do all your staff for each client and doesn't need to store info about rest of clients any longer.

Update My answer is ambiguous. I meant that Client constructor can do something like:

class Client {
    static int count = 0;
    public string Name { get; set; }
    public Client() {
        Name = string.Format("client{0}", count++);
    }
}

In this case class have static count this tells how many clients did we have. We doesn't use it in our code, but we can understand it while using current client by his name.

Upvotes: 0

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37113

Instead of creating n variables for n iterations, why not use a List<clinet> instead like so:

var clients = new List<client>();
for (int i = 0; i < int.MaxValue; i++)
{
    clients.Add(new client());
}

Or even simpler:

var clients = Enumerable.Range(0, int.MaxValue).Select(x => new client()).ToList();

Or still simpler:

var clients = Enumerable.Repeat(new client(), int.MaxValue);

Now you can access any client by it´s index, e.g.:

client c = clients[0];

Anyway be aware that you´re creating int.MaxValue number of client-instances. Depending on what client is you´re burning your memory.

NB: Please consider the naming-conventions, e.g. by calling classes like your client-class UpperCase: Client.

Upvotes: 1

Related Questions