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;
}
}
}
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?
shoushiPosted Jan 5, 2009, 8:53 PM
Assembly.Load(AssemblyPath).CreateInstance(ClassName);
Nilanka DharmadasaPosted Jan 5, 2009, 7:33 AM
Hi,
When you pass the class name to 'GetType' method don't forget to pass the namespace name.
Type t = Type.GetType(string.Format("GetConstructorTest.{0}", type));This is the solution for your issue.