0

Here is a string defining the class name.

string classname = "MyClass";

Here is the class.

class MyClass{ 
}

I want to use string for generictype.

ex)List<Myclass>

What should I do?

I tried this but it doesn't work.

List <Type.GetType($"ConsoleApp1.{classname}")> classlist;
playground
  • 75
  • 6
  • 1
    Does this answer your question? [Pass An Instantiated System.Type as a Type Parameter for a Generic Class](https://stackoverflow.com/questions/266115/pass-an-instantiated-system-type-as-a-type-parameter-for-a-generic-class) – madreflection May 07 '20 at 15:09
  • 1
    Can you explain why you want to use a non-specific class in your generic list? It sort of defeats the object of generics. You could just use `List`. – Neil May 07 '20 at 15:11

1 Answers1

0

Unfortunately, you can't just do that but you can use reflection to do this. An example would look like:

using System;
using System.Collections.Generic;

namespace StackOverflow
{
    public class MyClass
    {
    }

    public class Program
    {
        static void Main(string[] args)
        {
            string className = "StackOverflow.MyClass";

            // Generating the generic list
            var type = Type.GetType(className);
            var listType = typeof(List<>).MakeGenericType(new[] { type }); 
            var list = Activator.CreateInstance(listType);

            // Adding a value to the list
            var value = new MyClass();
            list.GetType().GetMethod("Add").Invoke(list, new object[] { value });

            // Fetch a value of the list
            var myClass = (MyClass)list.GetType().GetMethod("get_Item").Invoke(list, new object[] { 0 });

            // Invoke methods of MyClass-instance
            Console.WriteLine(myClass.ToString());                                        

            // Keep console open
            Console.ReadLine();
        }
    }
}

As madreflection has mentioned in the comments above, you can find additonal examples here.

To clear things up a bit, you could use a list of object instead of creating the list via reflection.

string className = "StackOverflow.MyClass";
var type = Type.GetType(className);

// Generating the list of objects
var list = new List<object>();

// Adding a value to the list
var value = Activator.CreateInstance(type);
list.Add(value);

// Fetch a value from the list
var myClass = (MyClass)list[0];

// Invoke methods of MyClass-instance
Console.WriteLine(myClass.ToString());
oRole
  • 1,316
  • 1
  • 8
  • 24