I have class Cat
and it has one attribute Name
and one method SayMiau
, I want to create an array of Cat
s with 10 instances which have different names like cat1 cat2 and etc and later in a loop call the method SayMiau
for all of them in a loop.
Cat[] cats = new Cat[10];
int id = 1;
foreach(Cat cat in cats){
cat.Name = $"Cat{id}";
id ;
}
foreach(Cat cat in cats){
cat.SayMiau(cat.Name);
}
class Cat{
public string? Name;
public static void SayMiau(string name){
Console.WriteLine("Cat{0} said Miauuuuu!",name);
}
}
CodePudding user response:
You haven't really explained your problem, but I can assume what it is from your code.
Here:
Cat[] cats = new Cat[10];
You define an array of Cats. But this is not what you think it is. All you are actually doing is saying that your array will contain a maximum of 10 objects of type Cat, but each element in the array is still null (albeit of type Cat). There are no Cat instances inside it at this stage and you still need to initialise and add them into the array individually.
so then here:
foreach(Cat cat in cats){
cat.Name = $"Cat{id}";
id ;
}
You are trying to assign values to each Cat in your array. But as said, the Array doesn't yet have any Cat instances, so you are trying to add values to nothing, which doesn't work.
Also, a foreach
statement uses an immutable collection, meaning that you can't amend values within the list. So you can't create a new Cat object within this loop. So you need to use a for loop instead.
So you should have
Cat[] cats = new Cat[10];
int id = 1;
for(int ind = 0; ind < cats.Length; ind ){
Cat cat = new Cat();
cat.Name = $"Cat{id}";
id ;
cats[ind] = cat;
}
Also, the SayMiau
method needs amending.
You need to remove static, and remove the signature. It is a Class method so no static needed and it should use the Name value within the class, not have it passed. So it should be
class Cat
{
public string? Name;
public void SayMiau()
{
Console.WriteLine("Cat{0} said Miauuuuu!", Name);
}
}
Then your calling statement should be
foreach (Cat cat in cats)
{
cat.SayMiau();
}
CodePudding user response:
You can try to use Linq to initialize the array with values needed.
Example
var emptyCats = new Cat[10]; // array with 10 *empty* elements
var cats = emptyCats.Select((_, i) => new Cat { Name = $"Cat{i}" }); // go throug the array and transform it to initialized array
foreach (Cat cat in cats)
{
Cat.SayMiau(cat.Name); // miau
}
Explanation
The idea is pretty simple. You created an empty array and now just need to transform it to another, filled array. Select
takes a function that do exactly this. It transform one elment into any other element. So I passed a function that initialize an instance of the Cat class.
As a result - we have list of filled cats :)