Home All Groups Group Topic Archive Search About

How do i initialize an array using Reflection

Author
9 Mar 2007 12:42 AM
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

Author
10 Mar 2007 4:27 PM
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

AddThis Social Bookmark Button