1

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

1
  • Just to be sure, the User type is not in an assembly you already reference? Because then you should simply use var type = typeof(User); as your first step. Commented Feb 20, 2013 at 11:38

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

4 Comments

this is not working me i have mentioned my class is in different project how can i get the reference of that assembly?
@ImranRashid: You mentioned that it was in a class library project, but you didn't say where this code was running. That's why it's important to be clear. Will edit.
Type.GetType("BOEntities.User") is returning null. I am running it in Unit Test project
@ImranRashid: Did you read my edit? And if you know the name at compile-time, why don't you just use typeof?
2

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

Comments

0

Try

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.