Don't ask me why, but I need to do the following:
string cName = "ClassA";
List<cName> l = new List<cName>();
How can I do it?
my code:
public void MergeForm(List<object> lModel)
{
string className = lModel[0].GetType().Name;
List<className> list = new List<className>();
}
object - it is a class
Use Assemmbly.GetTypes
:
var l = Assembly.GetTypes().Where(t => t.Name == "ClassA").ToList();
If you have the full type name, you can use Assemmbly.GetType
.
If you have the full type name and assembly-qualified name, and the type you seek is in another assembly, then use Type.GetType
.
You cannot have List<cName>
as static type, but you can create the instance:
IList l = (IList)Activator
.CreateInstance(typeof(List<>)
.MakeGenericType(Type.GetType(cName)));
cName
needs to be the fully qualified name, though.
Take a look at the Activator.CreateInstance method.
Type ac;
string cName = "ClassA";
switch (cName)
{
case "ClassA":
ac = typeof(ClassA);
break;
case "ClassB":
ac = typeof(ClassB);
break;
default:
ac = typeof(System.String);
break;
}
var genericListType = typeof(List<>);
var specificListType = genericListType.MakeGenericType(ac);
var l= Activator.CreateInstance(specificListType);