Search code examples
c#reflection.net-assembly

Get class properties by class name as string in C#


Can I get class properties if i have class name as string? My entities are in class library project and I tried different methods to get type and get assembly but i am unable to get the class instance.

var obj = (object)"User";
var type = obj.GetType();
System.Activator.CreateInstance(type);

object oform;
var clsName = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance("[namespace].[formname]");

Type type = Type.GetType("BOEntities.User");
Object user = Activator.CreateInstance(type);

nothing is working


Solution

  • I suspect you're looking for:

    Type type = Type.GetType("User");
    Object user = Activator.CreateInstance(type);
    

    Note:

    • This will only look in mscorlib and the currently executing assembly unless you also specify the assembly in the name
    • It needs to be a namespace-qualified name, e.g. MyProject.User

    EDIT: To access a type in a different assembly, you can either use an assembly-qualified type name, or just use Assembly.GetType, e.g.

    Assembly libraryAssembly = typeof(SomeKnownTypeInLibrary).Assembly;
    Type type = libraryAssembly.GetType("LibraryNamespace.User");
    Object user = Activator.CreateInstance(type);
    

    (Note that I haven't addressed getting properties as nothing else in your question talked about that. But Type.GetProperties should work fine.)