Main class ....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1{
class Program{
static void Main(string[] args){
string className = "Demo";
string namespaceName = "ConsoleApplication1";
var myObj = Activator.CreateInstance(namespaceName, className);
Console.Read();
}
}
}
Other class ....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1{
class Demo{
public void printClassName() {
Console.WriteLine("Demo");
}
}
}
This simple program has runtime error at
var myObj = Activator.CreateInstance(namespaceName, className);
line.
System.TypeLoadException {"Could not load type 'Demo' from assembly 'ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.":"Demo"}
Please help me to solve this error!.
Activator.CreateInstance(string, string)
doesn't do what you think it does.
The first parameter is the assembly name. The second parameter is the fully-qualified type name.
So you should have:
string className = "ConsoleApplication1.Demo";
string assemblyName = "ConsoleApplication1";
var myObj = Activator.CreateInstance(assemblyName, className);
(Assuming it's compiled into an assembly called ConsoleApplication1
of course.)
If you're able to get a handle to the Assembly
in a different way, however, you can use Assembly.GetType(string)
and then Activator.CreateInstance(Type)
.
See more on this question at Stackoverflow