Is Cast <T> implementation implemented against Linq's immutable style?

Here's how to Cast<T>implement it as part of:

public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source)
{
    IEnumerable<TResult> enumerable = source as IEnumerable<TResult>;
    if (enumerable != null)
    {
        return enumerable; //the culprit
    }
    return Enumerable.CastIterator<TResult>(source);
}

The problem I see is that it Cast<T>returns the actual enumerated itself if some criterion is met. For example, this should not be:

var x = new List<string> { "1" };
var y = x.Cast<string>();

x.Add("2"); //reflects in y "immediately", since they are the same reference.

Or maybe a more practical example:

object[] x = new[] { "1" };
var y = x.Cast<string>();

x[0] = "2"; //reflects in y "immediately", since they are the same reference.

The documentation page even says: This method is implemented using deferred execution., But not in every case (as shown above). In the same way, I can think of it AsEnumerableas another culprit who is returning himself.

The situation in which he may disconnect:

var x = new List<string> { "1" }; //data source
var y = x.Cast<string>(); //query


((List<string>)y).Add("2"); //did something with the query

// Whoa, got the data source itself changed by tinkering the query

Questions:

  • AsEnumerable Cast Linq? , ?

  • System.Linq, ?


, , , linq , . , .

, , . , IEnumerable<T>, linq, ( ) . , :

var x = new List<int> { 1 };
var y = x.Cast<SomeEnum>();

x.Add(2); //at this stage the change to x is not reflected in y yet

, x, y , x y. , , , , . , , y. , . , .

+4
2

, , , . , .

, CastIterator. , .

# , Linq () , .

# .

Linq . Linq. , : , ToArray(), .

+5

. LINQ, , LINQ IEnumerable, .

IEnumerable, LINQ, .

+3

All Articles