Reputation: 3502
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
Upvotes: 1
Views: 4090
Reputation: 1503290
I suspect you're looking for:
Type type = Type.GetType("User");
Object user = Activator.CreateInstance(type);
Note:
mscorlib
and the currently executing assembly unless you also specify the assembly in the nameMyProject.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.)
Upvotes: 4
Reputation: 1039418
Can I get class properties if i have class name as string?
Of course:
var type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();
This will get a list of public instance properties. If you need to access private or static properties you might need to indicate that:
var type = obj.GetType();
PropertyInfo[] properties = type.GetProperties(BindingFlags.NonPublic);
Upvotes: 2