Create List<T> from Name of class

Lance James 371 Reputation points
2022-03-12T17:28:29.563+00:00

I have a string containing a class name. The class name represents the map of a JSON file.

I need to use the name of the class contained in the string to create a List of the class type.

This represents the concept.

string myClass = "ClassTypeNeeded"

Type classType = Type.GetType(myClass);

Private List<classType> _classType;

The compiler error is: 'classType' is a variable but is used like a type.

Regards,
Lance

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-03-12T21:40:55.957+00:00

    Although I'm sure there is more to this question I'm going to give you exactly what is asked. If this answers your question mark it as answered and any following up questions start a new thread as the next part for adding items deserves another thread.

    I will say that this approach although works is best to find another solution to the task at hand rather than digging into reflection.

    Let's say we want to create an instance of a Car class

    public class Car 
    {
        public int Id { get; set; }
        public string Model { get; set; }
        public string Manufacturer { get; set; }
    }
    

    Step 1

    Add this method used later to create an instance of car in this case

    public static string CurrentAssembly() =>
        Path.GetFileNameWithoutExtension(
            Assembly.GetExecutingAssembly()
                .ManifestModule.Name);
    

    Step 2, using reflection create an instance of car note Car spelled out, if Car does not exists, code will throw an exception.

    var currentAssembly = CurrentAssembly();
    
    ObjectHandle classHandle = Activator.CreateInstance(null, 
        $"{currentAssembly}.Car");
    
    object created = classHandle.Unwrap();
    Type type = created.GetType();
    

    Step 3, method used to create the list

    public IList ListFromType(Type type)
    {
        var listType = typeof(List<>);
        var constructedType = listType.MakeGenericType(type);
    
        return (IList)Activator.CreateInstance(constructedType);
    
    }
    

    Step 3 create the list

    IList list = ListFromType(type);
    

    That satisfies your question.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.