0

i want to get property and methods of an object, starting from a string value.

I had the string value that represents the name of a class.

I do something like this

string p = "Employee";
Type emp = Type.GetType(p);
object empObj = Activator.CreateInstance(emp);

But object is null,because emp in null too... something is wrong

ArghArgh
  • 356
  • 3
  • 27
  • 1
    Your code is wrong. You must use the assembly qualified name for a type. Similar to "System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089". So not just the namespace + type name but also the assembly it is stored in. Required so the CLR can figure out what assembly it needs to load to find the type. – Hans Passant May 04 '14 at 14:07

3 Answers3

2

You must use the full assembly name or namespace when using reflection.

Example in your case:

string p = "MyNamespace.Employee";

As another example, for the System.Windows.Forms class you would use:

string p = "System.Windows.Forms.Form, " + 
"System.Windows.Forms, Version=2.0.0.0, Culture=neutral, " + 
"PublicKeyToken=b77a5c561934e089");

See more, how to get class reference from string?

If you do not know your full name, you can use the AssemblyQualifiedName property to get it.

Console.WriteLine(typeof(Employee).AssemblyQualifiedName);
Community
  • 1
  • 1
Cyral
  • 13,999
  • 6
  • 50
  • 90
1

Add namespace

string p = "Employee";
string namespace = "MyNamespace"
object empObj = Activator.CreateInstance(namespace, p);

Or

string p = "Employee";
string namespace = "MyNamespace"
Type emp = Type.GetType(namespace + "." + p);
object empObj = Activator.CreateInstance(emp);
binard
  • 1,726
  • 1
  • 17
  • 27
1

Type.GetType(string) requires that the string parameter is an AssemblyQualifiedName. In order to locate the constructor for the type of object you want to create, the Activator class need to know the namespace, the Assembly in which it is contained, along with its version, as well as the name of the type of the object itself.

For example:

string p = "MyNameSpace.Employee, MyAssembly, Version=1.4.1.0, Culture=neutral, PublicKeyToken=e7d6180f3b29ae11"
Type emp = Type.GetType(p);
object empObj = Activator.CreateInstance(emp);

If the range of types you have to handle like this is small and known at compile time, you may be better off using a simple switch statement. Alternatively, if the types may be contained in other Assemblies, such as plug-in DLLs, look at MEF and decorating the classes with Metadata that you can access from Factory objects to construct the instance of the correct type.

Evil Dog Pie
  • 2,300
  • 2
  • 23
  • 46