Why are IEnumerable Projections not immutable?

Assuming my Awesome class has a Bazinga property, which is a String with a default value of "Default", I could go:

  var enumerableOfAwesome = Enumerable .Range(1, 5) .Select(n => new Awesome()); foreach (var a in enumerableOfAwesome) a.Bazinga = "New value"; 

As you already know, recounting enumerableOfAwesome again will not make you happy if you expect to find the "New Value" strings safely hidden in all of Bazinga . Instead, their output to the console will look like this:

Default value
Default value
Default value
Default value
Default value

(.NET Fiddle here)

This is all good and dandy from some deferred point of execution, and this issue has already been discussed earlier, for example, here and. However, my question is why enumerator implementations do not return immutable objects; If perseverance over several enumerations is not guaranteed, then what is their ability to set values, except that people get confused?

This may not be a good question, but I'm sure your answers will be helpful.

+5
source share
2 answers

However, my question is why enumeration implementations do not return immutable objects

How do you expect them to do this? They are sequences of any type - what would you expect from something like:

 var builders = new string[] { "foo", "bar" }.Select(x => new StringBuilder(x)); 

? Do you expect this (regardless of "in this case") to create a new type automatically with the same API as StringBuilder , but magically make it immutable? How will he detect mutations?

Basically, what you ask is unacceptable - you can have a sequence in which the element type is changed, so when you repeat through it, you can mutate the object referenced by the link. Waiting for something else is unrealistic, IMO.

+9
source

Enumerators are not intended to ensure immutability. They represent the path to the loop in the form of collections, for example, when cycling through standard arrays with indexes. Since you can access underlying objects, this means that you can change them. And immutability in C # is something new in terms of collections, and it would be unexpected and impossible to implement in Enumerators.

0
source

All Articles