2
Answers

How can I use a string for the class name and get the constructor dynamically?

Ask a question
Lawrence

Lawrence

15y
3k
1
Hi, first post :) 
Ok here's what I'm trying to do:

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Reflection;
using System.Runtime.Remoting;
using System.Drawing;
using System.Windows.Forms;


namespace GetConstructorTest
{
    public class GooConsistency
    {
        public GooConsistency()
        {
        }
    }

    public class Monster
    {
        public Monster()
        {
        }
    }
    public class GooeyMonster: Monster
    {
        public GooeyMonster(GooConsistency gooness)
        {
        }
    }
    public class SqueltcheyMonster : Monster
    {
        public SqueltcheyMonster(Color tongueColor, bool isBackflipping)
        {
        }
    }

    public partial class Form1 : Form
    {
        public Form1()
        {
            object[] MonsterData1 = new object[] { new GooConsistency() };
            Monster Monster1 = CreateMonster("GooeyMonster", MonsterData1);
        }
        public Monster CreateMonster(string type, Object[] vConstructorArgumentValues)
        {
            Type[] argtypes = Type.GetTypeArray(vConstructorArgumentValues);
            Type t = Type.GetType(type);
            ConstructorInfo info = t.GetConstructor(argtypes);

            return info.Invoke(vConstructorArgumentValues) as Monster;
        }
    }
}

But on the line: ConstructorInfo info = t.GetConstructor(argtypes);

I get this exception:

System.NullReferenceException was unhandled
  Message="Object reference not set to an instance of an object."
  Source="GetConstructorTest"
  StackTrace:
       at GetConstructorTest.Form1.CreateMonster(String type, Object[] vConstructorArgumentValues) in G:\Portable Documents\Visual Studio 2008\Projects\GetConstructorTest\GetConstructorTest\Form1.cs:line 50
       at GetConstructorTest.Form1..ctor() in G:\Portable Documents\Visual Studio 2008\Projects\GetConstructorTest\GetConstructorTest\Form1.cs:line 44
       at GetConstructorTest.Program.Main() in G:\Portable Documents\Visual Studio 2008\Projects\GetConstructorTest\GetConstructorTest\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

Why?

Answers (2)