The only way to be convinced of reflection, but in 90% of cases you can avoid cost of it, using array is T[] . Most people are going to pass a correctly printed array, so that will do it. But, you should always provide a code for checking reflection, just in case. This is what my common boiler stove looks like (note: I wrote it here from memory, so this may not compile, but this should give the main idea):
class MyCollection : ICollection<T> { void ICollection<T>.CopyTo(T[] array, int index) { // Bounds checking, etc here. CopyToImpl(array, index); } void ICollection.CopyTo(Array array, int index) { // Bounds checking, etc here. if (array is T[]) { // quick, avoids reflection, but only works if array is typed as exactly T[] CopyToImpl((T[])localArray, index); } else { Type elementType = array.GetType().GetElementType(); if (!elementType.IsAssignableFrom(typeof(T)) && !typeof(T).IsAssignableFrom(elementType)) { throw new Exception(); } CopyToImpl((object[])array, index); } } private void CopyToImpl(object[] array, int index) { // array will always have a valid type by this point, and the bounds will be checked // Handle the copying here } }
EDIT : Alright, forgot to say something. The couple naively uses what is read only as element.IsAssignableFrom(typeof(T)) in this code. You must also enable typeof(T).IsAssignableFrom(elementType) , as BCL does, if the developer knows that all values ββin this particular ICollection actually of type S , obtained from T , and pass an array of type S[]
source share