Question How do I use Activator.CreateInstance (string,string) ?

Gar

New member
Joined
Dec 31, 2015
Messages
2
Programming Experience
10+
I have two projects. From Project1 I want to use the Activiator.CreateInstance(string,string) method to create an object that is in Project2. Project1 does not have a reference to Project2. I have read online a lot today but have not found anything like this. I must not completely understand the meanings of assembly and TypeName. They don't seem complicated but my code does not work. Here is my simple code that fails. My project1 is ActivatorPlayMain and project2 is ActivatorPlayObjects which is a class library.

C#:
          using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;


namespace ActivatorPlayMain
{
    class Program
    {
        static void Main(string[] args)
        {
            String assemb = @"C:\Users\Gary\Documents\Visual Studio 2015\Projects\ActivatorPlayMain\ActivatorPlayObjects\bin\Debug\ActivatorPlayObjects.dll";
            System.Reflection.AssemblyName n = System.Reflection.AssemblyName.GetAssemblyName(assemb);
            Console.WriteLine(n.FullName);
            var x = Activator.CreateInstance(assemb, "ActivatorPlayObjects.Class1");
  Console.Read();


        }
    }
}
 
Wow. After reading and trying all morning to get this to work I used the Activator.CreateInstanceFrom(string,string) which works and is probably correct for this scenario. I also got a better understanding of the assembly qualified name and the use of Type.GetType("ActivatorPlayObjects.Class1,ActivatorPlayObjects") which when used correctly does work. Thanks.
 
Back
Top Bottom