-1

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

Sultan
  • 319
  • 3
  • 11
  • Possible dupe: http://stackoverflow.com/questions/1044455/c-sharp-reflection-how-to-get-class-reference-from-string – Saturnix Oct 24 '13 at 11:48
  • 3
    I don't like "Don't ask me why". If we know why, we can maybe offer a better solution. In software development theres almost always more then one road to rome. – Marco Oct 24 '13 at 11:55
  • 1
    Why do you want to do this? :) – Kjartan Oct 24 '13 at 12:02

4 Answers4

3

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.

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
  • Thanks for answer, but it's throws exception: An object reference is required for the non-static field, method, or property 'System.Reflection.Assembly.GetTypes() – Sultan Oct 24 '13 at 11:59
  • @Sultan Hard to guess. Perhaps show some more of your code. Also, the methods I've described are very commonly used, you shouldn't have any problems in finding some examples (starting with the links I provided). – BartoszKP Oct 24 '13 at 12:03
3

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.

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Tobias Brandt
  • 3,393
  • 18
  • 28
0

Take a look at the Activator.CreateInstance method.

Krzysztof Cieslak
  • 1,695
  • 13
  • 14
0
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);
Rakin
  • 1