0

First off, I just wanna take a second to assure all readers here that I'm not 'proficient' in C#, and thus an answer may be obvious (though I couldn't find one when searching).

I currently have a EnumerableUtility custom class to convert data types (usually Enumerables, though sometimes other data types) into an object[] array. I'm using a very sloppy method which essentially goes like this:

class EnumerableUtility
{
    private IReadOnlyCollection<object> data;
    public EnumerableUtility(IReadOnlyCollection<object> x)
    {
        data = x;
    }
    public object[] ConvertToArray()
    {
        object[] info = { };
        // Here's where I think the exception is raised
        foreach (object obj in data)
            info[info.Length] = obj;
        return info;
    }
}

Again, sorry for both horrible code, sloppy methods and slight ignorance, but I kinda want to sort this out into a proper 'array' for easier management. Is there any way to do this? Thanks.

Cryogenic
  • 81
  • 7

2 Answers2

1

Your array object[] info = { }; HAS BOUNDS its bound to ZERO (1 element). What you need to be doing is creating an array of the length of the incoming data Such as.

object[] info = new object[data.Count];

Next your array converting is incorrect you are setting the index to the Length of your array. This will always be out of range as arrays are Zero Index Based (ie the first array item is at the index 0 not 1).

Finally if you were to change to info.Length-1 for your index would mean that you will only ever set the LAST element on every loop. Which sort of negates the loop as you can simply assign the last element in the array to the last element in the collection. I have rewritten the method for you to convert the ReadOnly collection to an array.

public object[] ConvertToArray()
{
    object[] info = new object[data.Count];
    var i = 0;
    // Here's where I think the exception is raised
    foreach (var obj in data)
        info[i++] = obj;
    return info;
}

Now this will return an object array from your collection. However this is completly uneeded as it reinvents an very big wheel.

We already have an extension method on every IEnumerable to convert it to a typed array.

var c = (object[])data.ToArray();

One line (no extra methods) to convert your collection to an array.

  1. Enumerable.ToArray()
  2. List<T>.ToArray()
  3. ArrayList.ToArray()
Nico
  • 12,493
  • 5
  • 42
  • 62
0

You can not assign a value to the element with index info.Length. You should do something like this:

object[] info = new object[data.Length];
int i = 0;
foreach (object obj in data)
   info[i++] = obj;
Brian
  • 5,069
  • 7
  • 37
  • 47
Diabolus
  • 268
  • 2
  • 15