How do i initialize an array using Reflection

K

Kishore

Hi
I have a class (type - MyClass). I need to create an instance of this
class and then create an array of type MyClass and intialize this
array with the instance.

I am able to create the class and array but not sure how to
initialize.

Type myClassType = Type.GetType("MyClass,MyAssembly");
ConstructorInfo cinfo = myClassType.GetConstructor(new Type[]{});
object myClassObj = cinfo.Invoke(null);

Type myClassArrayType = Type.GetType("MyClass[], MyAssembly");
cinfo = myClassArrayType.GetConstructor(new Type[]{typeof(int)});
object myClassArray = cinfo.Invoke(new object[]{1});

//HOW CAN I DO myClassArray[0] = myClassObj using Reflection.

Please suggest
Thanks
 
O

Oliver Sturm

Hello Kishore,

This seems to work fine for me:

[TestFixture]
public class Tests {
[Test]
public void Test( ) {
Type myClassType = Type.GetType("ReflectionInitArray.MyClass");
object myClass = Activator.CreateInstance(myClassType);
Assert.IsNotNull(myClass);

Type arrayType = Type.GetType("ReflectionInitArray.MyClass[]");
object myArray = Activator.CreateInstance(arrayType, new object[] { 1 });
Assert.IsNotNull(myArray);

arrayType.InvokeMember("SetValue", BindingFlags.Instance |
BindingFlags.InvokeMethod | BindingFlags.Public, null, myArray, new
object[] { myClass, 0 });
Assert.AreEqual(myClass, ((MyClass[]) myArray)[0]);
}
}

public class MyClass {
public MyClass( ) { }
}

Calling into SetValue is what the array indexer would otherwise do, so it
seems like a good way. Of course you could also try going through the
actual indexer, but I don't see a point to that.


Oliver Sturm
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top