-3

My function accepts array as object ass well as the type by System.Type variable. I want to convert it to Array of Type(T[]).

void doSomething(object arrayData, Type arrayType)
{
  // here i want to convert arrayData object to arrayType[] type.
  // because I need to call a function foo<T>(T[] array) here. 
}

How will convert dynamically according to Type variable ??

vrnithinkumar
  • 1,273
  • 1
  • 11
  • 29

2 Answers2

1

So, arrayType is the type you want to cast arrayData to. So for example, if you pass typeof(int) as arrayType, you want to cast arrayData into int[].

While you could do this using reflection, you don’t really get any benefit from it: The type is only known at compile time, so any conversion would only be there at compile time, so you won’t get any type safety from it, and as such couldn’t access the data.

You could only cast arrayData to object[] to at least get access to the array itself:

void DoSomething(object arrayData, Type arrayType)
{
    object[] data = (object[])arrayData;
    // do something with data
}

Alternatively, you could also create a (private) generic method that takes the data and then converts it into a typed array:

private void DoSomethingGeneric<T>(object arrayData)
{
    T[] data = (T[])arrayData;
    // do something with data
}

This would give you access to the type. You could call that method using reflection from the non-generic DoSomething

public void DoSomething(object arrayData, Type arrayType)
{
    MethodInfo mi = this.GetType().GetMethod("DoSomethingGeneric").MakeGenericMethod(arrayType);
    mi.Invoke(this, new object[] { arrayData });
}

But even with the generic method, you still have one problem: What do you want to do with that T[] that you couldn’t do with an object[]?

poke
  • 369,085
  • 72
  • 557
  • 602
0

You could simply just cast your arrayData to the target type or - and this is more defensive - handle your array as an object[] and get the elements with the matching type T by calling OfType<T>():

    static void doSomething<T>(object arrayData)
    {           
        var arr1 = (arrayData as T[]);
        var arr2 = (arrayData as object[]).OfType<T>().ToArray();

        // call foo() with arr1 on arr2
    }

Of course it would be nicer to change the signature to:

    static void doSomething<T>(T[] arrayData)
    {           
        // do anything before ...
        foo(arrayData);
        // do anything after ...
    }

... but then foo has to support T as well:

    static void foo<T>(T[] arr)
    {
    }
Waescher
  • 5,361
  • 3
  • 34
  • 51
  • But as I mentioned in the comments `void doSomething(object arrayData, Type arrayType)`cant be changed to `void doSomething(object arrayData)` – vrnithinkumar Aug 17 '15 at 11:44