Search code examples
c#arrayslistgeneric-programming

Creating Array from type object


I am trying to create an array of the type that is known and currently set to Type. I have been able to create an IList of the type but I am still able to convert that to an array of the type, getting object[] instead.

object propertyValue; //This needs to be an object since it can be set to any object
Type currentType = PropertyInfo.GetType(); //Example: System.String
propertyValue = GetArray(reader, currentType); //What would this look like to make currentType work?
//Reflection occuring later to set propertyValue to attribute of String[]

Here what I got what working with IList, the issue here is not sure how to cast it to an array of currentType. I also prefer just getting an array back instead:

private IList GetArray(Reader reader, Type currentType)
{
  var returnList = createList(currentType); 
  //reader loop that appends to list
  return returnList;
}

public IList createList(Type currentType)
{
  Type genericListType = typeof(List<>).MakeGenericType(currentType);
  return (IList)Activator.CreateInstance(genericListType);
}

Solution

  • Here's an even easier way:

    var stringType = typeof(string);
    var anArray = System.Array.CreateInstance(stringType, 5);
    var arrayAsArray = (object[]) anArray;
    

    At that point, the variable anArray is typed as an object, but refers to an array of 5 strings. The variable arrayAsArray is typed as object[] and it refers to that same array of strings.

    What you can't get (as far as I know) is a variable that it typed MyType[] referring to an array of MyType instances if all you have is typeof(MyType). The compiler creates typed object references at compile time, you don't get to play in that space.

    One of the features of the .NET Framework (or flaws, depending on how you look) is that arrays are covariant. There are lots of things that can go bad with array covariance (for example, since the compiler thinks you have an `object[]', it would let you try to add an Elephant instance into your array of strings). However, in this case, it makes your code usable, even if it is somewhat fragile.