views:

103

answers:

2

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?

+7  A: 

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.)

Jon Skeet
Shouldn't we say anything about this might be bad design? The caller being able to change the list and why didn't the method take an array in the first place?
Steven
+4  A: 

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.

Paul Ruane
Even if a conversion *does* exist, it won't be used - because the compiler doesn't know about it at compile time.
Jon Skeet
@Jon: not sure I follow — I have just tested with an explicit conversion and it cast fine. Edit: I take it back (mistake in my test). You are indeed correct.
Paul Ruane