0

If I create an instance of a class with a string name, e.g.

    public static object GetInstance(string strFullyQualifiedName) {
        Type type = Type.GetType(strFullyQualifiedName);
        if (type != null)
            return Activator.CreateInstance(type);
     }

which returns an object:

            object myClass = GetInstance("MyClassName");

How can I then pass this object 'myClass' as T to a method?

        public static List<T> CreateListAndAddEmpty<T>() where T : new() {
        List<T> list = new List<T>();
        list.Add(new T());
        return list;
    }

var myList = CreateListAndAddEmpty<myClass>();

It doesn't accept myClass?

'myClass' is a variable but is used like a type

Any ideas how to create a class from string name, which can be used as T?

Thanks,

thegunner
  • 6,883
  • 30
  • 94
  • 143
  • 1
    Generics need to have the type at compile time. – TheGeneral Jul 29 '18 at 11:30
  • You should take a look at https://stackoverflow.com/questions/9857180/what-does-t-denote-in-c-sharp . – Azhy Jul 29 '18 at 11:31
  • You’ll have to use reflection to invoke the method: https://stackoverflow.com/questions/232535/how-do-i-use-reflection-to-call-a-generic-method – Dave M Jul 29 '18 at 11:32
  • Every time I see a question that involves converting a `string` into a specific type, it's almost always an XY problem or should be done in a different way. Perhaps if you explain why you are doing this, we could come up with a better idea altogether? – DavidG Jul 29 '18 at 11:51

1 Answers1

0

The generic type parameter wants the name of the type, not an instance of the type. You would need <MyClassName> and it would only allow you to add instances that you had cast to MyClassName.

If you know the name of the type at compile time (if you can type the name in your source code), you can use the generic type constraint, but then you shouldn't be using reflection to create the instance in the first place. If you want to use new T() then you don't need to use Activator.CreateInstance to create the instance, because new does that for you.

It's very rare that you should ever need to directly use reflection. Where I work, it's just banned outright.

If you don't know the type at compile time (e.g. if the user enters the name of the type while it is running), you can't use the generic type constraint. You could use the non-generic ArrayList or List<object>, but you would have to try to cast items in the collection to the type you expect them to be when you use them.

George Helyar
  • 4,319
  • 1
  • 22
  • 20