Dan Brenner
Dan Brenner

Reputation: 898

Modifying an IEnumerator after declaration

I have been working with Unity C#. I do not really understand IEnumerators, but suppose I have the following:

IEnumerator some_function(int a) { ... }

IEnumerator f = some_function(0);

Is there a way to change the parameter value of an existing f so that it is equivalent to having declared, for instance:

IEnumerator f = some_function(5);

Upvotes: 2

Views: 60

Answers (2)

user743382
user743382

Reputation:

If you've not yet started enumerating over the results of your function, there's no problem at all with simply calling your function again:

IEnumerable f = some_function(0);
f = some_function(5);

If you have started enumerating over the results of your function already, and you want the existing invocation to continue with the new value, then consider a helper class:

class SomeFunctionData {
  public int a;
}

IEnumerable some_function(SomeFunctionData data);

and then

var data = new SomeFunctionData { a = 0 };
IEnumerable f = some_function(data);
...
data.a = 5;

If some_function continues looking at the existing SomeFunctionData instance, from then on, it will see the new value for a. Note that under most circumstances, this leads to a hard-to-understand program logic, so check if you really need this before implementing it, but there are some cases where it's useful.

Upvotes: 2

nvoigt
nvoigt

Reputation: 77354

The short answer is No.

You could call your method again obviously. Or you could package your behavior in a new class or method. But the IEnumerable<> or the used enumerator have no connection to the producer that would allow this.

Upvotes: 4

Related Questions