Click here to Skip to main content
15,922,512 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

There are some questions and answers about this topic but, none of them solve my issue. I am a quite new about c#.

I've a class and had a string value. If the string value same with class name, create new object from that class.

string value is "Basic"
and class name is "Basic"

I know the solution is Assembly.CreateInstance but it always gets null , could not success to create any instance.

Name:TTT Publickeytoken=null
CodeBase: path to TTT.exe file

What I have tried:

namespace TTT
{ 
    public class Basic
    {
        public string Id { get; set; }
        public int SourceSystem { get; set; }
    }
 public class Message_Tag_Info
    {
        public string Id { get; set; }
        public string ClassCode { get; set; }
        public string ClassName { get; set; }
    }

   class Program
    {
        static void Main(string[] args)
        {
            Message_Tag_Info message = new Message_Tag_Info();
            
            string tmp = "Basic";
            message.ClassName = tmp;


           Type t = Type.GetType("TTT."+message.ClassName);

           Assembly assem = Assembly.GetAssembly(t);
           Console.WriteLine("Name: {0}", assem.FullName);        
           Console.WriteLine("CodeBase: {0}", assem.CodeBase);

       var obj = Assembly.GetExecutingAssembly().CreateInstance(message.ClassName);

           Console.ReadLine();

        }
        
    }
}
Posted
Updated 9-Oct-17 2:51am

 
Share this answer
 
Comments
Member 13454019 10-Oct-17 4:21am    
thanks
You're doing CreateInstance on just "Basic" and that's not enough for reflection to work out what class you mean, it needs the full name of TTT.Basic

Below I use t.FullName instead

var obj = Assembly.GetExecutingAssembly().CreateInstance(t.FullName);
 
Share this answer
 
Comments
Member 13454019 10-Oct-17 4:21am    
thanks a lot, it works.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900