Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instantiate subclass by string na C#

Tags:

c#

I have a Class and a Sub Clas

namespace MyCode
{
    public class Class1
    {
        int a = 1;
        int b = 2;
        public class SubClass1
        {
            int a = 1;
            int b = 2;
        }
    }
}

Now I need to instantiate each class by string name. I can do this from the class, but not for the subclass.

This works:

var myObj = Activator.CreateInstance(Type.GetType("MyCode." + "Class1"));

But this, din´t work:

var myObj = Activator.CreateInstance(Type.GetType("MyCode." + "Class1.SubClass1"));

What I need to do for the second option?

like image 952
Antonio Rafael da Silva Filho Avatar asked Dec 08 '22 19:12

Antonio Rafael da Silva Filho


1 Answers

Whenever you don't know what a name should be you can see the name by checking typeof(MyCode.Class1.SubClass1).FullName.

When you have a subclass you use the + sign.

var myObj = Activator.CreateInstance(Type.GetType("MyCode." + "Class1+SubClass1"));
like image 173
Scott Chamberlain Avatar answered Dec 21 '22 18:12

Scott Chamberlain