Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does casting an IList<T> to an array of type T[] cause enumeration?

I have a method that looks like:

T[] field;

public Method(IList<T> argument)
{
    this.field = (T[])argument;
}

When the body of the method is executed does enumeration take place during the cast? Would that change if the underlying type was different?

like image 411
Brian Triplett Avatar asked Jan 26 '26 20:01

Brian Triplett


2 Answers

No, it won't enumerate anything. It will either succeed if argument actually is a T[], or throw an InvalidCastException exception if it isn't. (Or return null if argument is null.)

like image 50
Jon Skeet Avatar answered Jan 29 '26 08:01

Jon Skeet


If argument is a reference to an array (of type T), then there is no enumeration — it is a simple cast.

If argument is a reference to a List<T> or another class that implements IList then there will potentially be a casting exception. (I say potenially as there may be an implict or explict conversion to T[] — most likely there won't be).

Edit: as pointed out by Jon, a conversion won't be made in the generic method, so the above parenthesis is incorrect.

like image 34
Paul Ruane Avatar answered Jan 29 '26 08:01

Paul Ruane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!