Imran Rashid
Imran Rashid

Reputation: 3502

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

Upvotes: 1

Views: 4090

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1503290

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.)

Upvotes: 4

Tomtom
Tomtom

Reputation: 9394

Try

Type type = Type.GetType("Assembly with namespace");

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

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

Related Questions