Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 51761
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 10, 20262026-05-10T16:48:04+00:00 2026-05-10T16:48:04+00:00

Ok, my actual problem was this: I was implementing an IList<T> . When I

  • 0

Ok, my actual problem was this: I was implementing an IList<T>. When I got to CopyTo(Array array, int index), this was my solution:

void ICollection.CopyTo(Array array, int index) {     // Bounds checking, etc here.     if (!(array.GetValue(0) is T))         throw new ArgumentException('Cannot cast to this type of Array.');     // Handle copying here. } 

This worked in my original code, and still works. But it has a small flaw, which wasn’t exposed till I started building tests for it, specifically this one:

public void CopyToObjectArray() {     ICollection coll = (ICollection)_list;     string[] testArray = new string[6];      coll.CopyTo(testArray, 2); } 

Now, this test should pass. It throws the ArgumentException about not being able to cast. Why? array[0] == null. The is keyword always returns false when checking a variable that is set to null. Now, this is handy for all sorts of reasons, including avoiding null dereferences, etc. What I finally came up with for my type checking was this:

try {     T test = (T)array.GetValue(0); } catch (InvalidCastException ex) {     throw new ArgumentException('Cannot cast to this type of Array.', ex); } 

This isn’t exactly elegant, but it works… Is there a better way though?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-10T16:48:04+00:00Added an answer on May 10, 2026 at 4:48 pm

    The only way to be sure is with reflection, but 90% of the time you can avoid the cost of that by using array is T[]. Most people are going to pass a properly typed array in, so that will do. But, you should always provide the code to do the reflection check as well, just in case. Here’s what my general boiler-plate looks like (note: I wrote this here, from memory, so this might not compile, but it should give the basic 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: Ok, forgot to point something out. A couple answers naively used what, in this code, reads as element.IsAssignableFrom(typeof(T)) only. You should also allow typeof(T).IsAssignableFrom(elementType), as the BCL does, in case a developer knows that all of the values in this specific ICollection are actually of a type S derived from T, and passes an array of type S[]

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 93k
  • Answers 93k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Something like this works in IE 7 & FF 3… May 11, 2026 at 6:40 pm
  • Editorial Team
    Editorial Team added an answer If it were me, I'd put nicely targetable classes on… May 11, 2026 at 6:40 pm
  • Editorial Team
    Editorial Team added an answer With NHibernate, session factory creation is very expensive (so you'll… May 11, 2026 at 6:40 pm

Related Questions

I have the weirdest of problems. I have a jQuery function that animates the
The title is a bit more specific than my actual goal: I have a
Ok, so here is a problem analogous to my problem (I'll elaborate on the
Ok, let's see if I can make this make sense. I have a program

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.