-1

I'm trying to create a method that loops through an array and executes some actions I wrote with a lambda expression. Somehow I don't think I understood how to use actions correctly because my code just results in a bunch of "null" objects.

Does somebody know what I am doing wrong?

        public void forEach(Action<Neuron> action)
        {
            for(int i = 0; i < this.Neurons.Length; i++)
            {                
                action(this.Neurons[i]);
            }            
        }

        public void CreateNeurons(int AmountOfNeurons)
        {
            this.Neurons = new Neuron[AmountOfNeurons];
            this.forEach(x => x = new Neuron(AmountOfNeurons));
        }

Image of the result

LetsHenne
  • 55
  • 4
  • 1
    Why are you doing this? You don't need to do this. [You should use the `foreach` control statement, not an extension-method - there's dozens of separate reasons why this is a bad idea, including from Jon Skeet](https://stackoverflow.com/questions/200574/linq-equivalent-of-foreach-for-ienumerablet). – Dai Jun 29 '22 at 17:46
  • this.Neurons = = Enumerable.Range(1,AmountOfNeurons).Select( x=> new Neuron(AmountOfNeurons)).ToArray(); – yo chauhan Jun 29 '22 at 18:12

1 Answers1

2

In your delegate, setting x = ... only changes the value of that local parameter: it does nothing to the array itself. You would end up with the same problem if you used a for loop like this:

var a = new[] { 1, 2, 3};

for (int i = 0; i < a.Length; i++)
{
    var x = a[i];
    x = 5; // this does nothing to `a[i]`
}

Notably, a foreach loop would warn you if you tried to do this:

foreach (var x in a)
{
    x = 5; // CS1656: Cannot assign to 'x' because it is a foreach variable.
}

This supports Dai's comment: you really shouldn't be defining your own forEach method. There are plenty of better, more idiomatic ways to do anything you'd want to do with a method like this. A foreach construct would have told you exactly what you were doing wrong, for example. And creating an array with a bunch of items is typically simpler with LINQ:

this.Neurons = Enumerable.Range(0, AmountOfNeurons)
    .Select(_ => new Neuron(AmountOfNeurons))
    .ToArray();
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315