Reputation: 92
This is my first time, so... be gentle ;) Welcome community!
Here's my problem. I have to create multiple objects inside a loop. But I don't know how to do it. Already tried doing it this way:
List<myClass> ObjectList = new List<MyClass>();
and then :
ObjectList.Add(new MyClass(a,b));
Class is with descriptor and params "a" and "b" are set.
So, I'm looking for this :
class myClass
{
int a;
int b;
public MyClass(int A, int B)
{
a=A;
b=B;
}
class Main()
{
Random r=new Random();
MyClass a1 = new MyClass(r.Next(0,11));
MyClass a2 = new MyClass(r.Next(0,11));
MyClass a3 = new MyClass(r.Next(0,11));
MyClass a4 = new MyClass(r.Next(0,11));
MyClass a5 = new MyClass(r.Next(0,11));
MyClass a6 = new MyClass(r.Next(0,11));
}
}
And I have to find a way to create these objects in the loop, cause I cannot know how many of these will be, as I'm reading a matrix from a file.
Upvotes: 0
Views: 1198
Reputation: 109557
There is a common solution to the situation where you want to initialise something by repeatedly attempting to acquire an item from a source until the source runs out.
This is called a "loop-and-a-half" construct (and it's a proper "structured" construct, since it is a loop with a single exit).
The general approach goes like this:
while (true)
{
attempt to obtain next item;
if (no more items available)
break loop;
add item to collection;
}
A general implementation in C# might look like this:
class MyClass
{
}
class MyInitData
{
}
static class Program
{
static void Main(string[] args)
{
var list = new List<MyClass>();
while (true)
{
var initData = GetNextItem(); // Returns null when no more items are available.
if (initData == null) // No more items available.
break;
list.Add(CreateMyClassFromInitData(initData));
}
}
static MyInitData GetNextItem() // Returns null when no more items are available.
{
// Code to return next item. Implementation omitted here.
return null;
}
static MyClass CreateMyClassFromInitData(MyInitData initData)
{
// Create a new MyClass from initData. Implementation omitted here.
return new MyClass();
}
}
As another - simpler - example, here's how you might go about reading number strings from a text file and converting them into a list of ints, using a loop-and-a-half:
var list = new List<int>();
using (var reader = File.OpenText("MyFileName.txt"))
{
while (true)
{
string line = reader.ReadLine();
if (line == null)
break;
list.Add(int.Parse(line));
}
}
Upvotes: 2