Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new classes in for loop

Tags:

c#

.net

class

Currently I have the following code:

        DecisionVariable[] attributes = 
        {
            new DecisionVariable("Var1", 2),
            new DecisionVariable("Var2", 4),
            new DecisionVariable("Var3", 1),
            new DecisionVariable("Var4", 2),
            new DecisionVariable("Var5", 5),
        };

but I would like to create them using a For loop:

        DecisionVariable[] attributes = 
        {
            for (int i=0;i<49;i++)
            {
                new DecisionVariable ("Var" + i, iValues[i]);
            }
        };

In the second version C# tells me that "For" has an invalid expression.

Do I have a typo somewhere or is something like that generally not allowed, using a for loop in a constructor?

like image 858
tmighty Avatar asked Feb 14 '13 08:02

tmighty


People also ask

Can we use for loop in class?

A "For" Loop is used to repeat a specific block of code a known number of times. For example, if we want to check the grade of every student in the class, we loop from 1 to that number. When the number of times is not known before hand, we use a "While" loop.

How do you add a loop to a class in Java?

Java Infinitive for Loop If you use two semicolons ;; in the for loop, it will be infinitive for loop. Syntax: for(;;){ //code to be executed.

How do you loop multiple variables?

And you, too, can now declare multiple variables, in a for-loop, as follows: Just separate the multiple variables in the initialization statement with commas.


1 Answers

You can't use a for loop inside a collection initializer. Use this code instead:

DecisionVariable[] attributes = new DecisionVariable[49];
for (int i = 0; i < 49; i++)
    attributes[i] = new DecisionVariable ("Var" + i, iValues[i]);
like image 87
Daniel Hilgarth Avatar answered Oct 29 '22 21:10

Daniel Hilgarth