I have string "Car", and I would like to get the type Car
from it. My class Car is:
namespace MySolution.MyProjectA
{
public class Car
{
...
}
}
I trying getting type like this but it returns null:
Type myType = Type.GetType("MySolution.MyProjectA.Car"); // returns null
Given a string variable representing my type (i.e. "Car"), how do I get its Type Car?
UPDATE AND SOLUTION
Thanks to suggestion from @AsafPala here (Type.GetType("namespace.a.b.ClassName") returns null), I got it to work. Turns out if you are calling GetType from another project in your solution (which is another assembly), you have to provide also assembly name.
Since MySolution has 2 project MyProjectA and MyProjectB, these are 2 separate projects (or assemblies) in same solution so you need to provide fully specified assembly name of your type (that is MySolution.MyProjectA.Car
) and assembly name (that is MySolution.MyProjectA
) as comma separated as below:
Type myType = Type.GetType("MySolution.MyProjectA.Car,MySolution.MyProjectA");
UPDATE AND SOLUTION
Since I am calling this code in another project (which is same as assembly), I need to provide fully specified type name and assembly name as comma separated like so:
namespace MySolution.MyProjectB
{
public class MyClass
{
...
...
public void MyMethod()
{
// this wont work, I get null back
//Type myType = Type.GetType("MySolution.MyProjectA.Car");
Type myType = Type.GetType("MySolution.MyProjectA.Car,MySolution.MyProjectA"); //this works
...
}
}
}
namespace
around the class (it may not be the same as"MySolution.MyProject"
). – GrievanceGetType
from? Your code works fine for me. – Grievance