views:

287

answers:

4

Duplicate of What is the purpose/advantage of using yield return iterators in C#?

Okay it just not this. Can you explain me in details that how does the two different?

Like Returning an Array (Lets say string) or doing a yield return with iterator(also string)

I find them to be the same. Please go into detail.

+2  A: 

If you return an iterator that cannot change the internal data structure, you might not need to make a copy of it.

On the other hand, a common mistake is to return something you use internally, and this will allow outside code to modify your internal data structures, which is usually a big no-no.

For instance, consider the following:

Int32[] values = otherObj.GetValues();
values[0] = 10;

If the GetValues method simply returns an internal array, that second line will now change the first value of that array.

Lasse V. Karlsen
+1  A: 

Iterators cannot be modified but arrays can. You can reference specific items in an array using the [index] notation, but with iterators you can only go from the first element in order.

AgileJon
So if you want to a make DLL or class to return something to a thrid-party program(they using ours) you should use iterator?
Jonathan Shepherd
Exactly! That or return a copy of the array.
AgileJon
+2  A: 

An array is a data storage. An iterator is just an iterator over some other data storage or method that produces a sequence.

Thus if a method returns an array you can modify it and its elements. You cannot do that via an iterator. Also, an array is of limited size. An iterator could be infinite.

Brian Rasmussen
+8  A: 

An array is a pointer to a fixed sized, random-access chunk of data. The caller can update values, access values in any order etc.

An iterator is a key to a sequence of values (which could be infinite in length). The caller can only access them in the order supplied by the source, and cannot update them.

There is more overhead accessing each value in a sequence, but it has the advantage of not needing all the data at once, so can be more efficient for mid-to-long sequences.

Marc Gravell
You always answer my question on the point. Thanks!
Jonathan Shepherd