Want to show your appreciation? Please to my charity.

Wednesday, June 10, 2009

Create Arbitrary Bound Array in C#

I have a need create an arbitrary bound array when write test cases for implementation of ICollection.CopyTo. C# doesn't support it as language feature but luckily, the Array class does allow it. Here is an helper class to make the task easier:

        public static Array NewArray<T>(int from, int to)
            return Array.CreateInstance(
                typeof(T), // Array type
                new int[] { to - from + 1 }, // Size
                new int[] { from }); // lower bound

With that, I can create an array like this: Array sales = NewArray<double>(1995, 2009);

No comments:

Post a Comment