0

Is it possible to do something like this?

Type MyType = typeof(SomeClass);
SomeMethod<MyType>();

Where SomeMethod is,

T SomeMethod<T>() where T : TypeOfSomeClass {
   ...

   return NewInstanceOfT;
}

This fails, of course. I want to store the type of a class and later use that type (the value of MyType) as the generic type for a method.

This is an use case as an example:

class WindowService {
    public static T CreateWindow<T>() where T : Window {
        return (T)Activator.CreateInstance(typeof(T));
    }
}

... (in some other class) ...

Type TypeOfWindow = typeof(MyConcreteWindow);

void CreateAWindow() {
    Window Obj = WindowService.CreateWindow<TypeOfWindow>();
}

CreateWindow<T> should create an instance of whatever class is stored in TypeOfWindow, as long as it extends Window.

Gabriel
  • 2,170
  • 1
  • 17
  • 20
  • Not really. I want to use the value of `MyType` (which has type `Type`) as the generic type. I don't have an instance like him, just the type. – Gabriel Apr 02 '20 at 17:56
  • Take a closer look. `typeof(ClassWithSomeMethod).GetMethod("SomeMethod").MakeGenericMethod(typeof(SomeClass)).Invoke();` The key concept here is to take a generic method definition and make a close-constructed method definition, which you can then invoke. – madreflection Apr 02 '20 at 18:06
  • `typeof(WindowService).GetMethod("CreateWindow").MakeGenericMethod(TypeOfWindow).Invoke(...);` – madreflection Apr 02 '20 at 18:11
  • Understood. Thank you. – Gabriel Apr 02 '20 at 18:12

1 Answers1

0

If 'm not mistaken about what you want to accomplish, it's done like this:

public void MyMethod<T>(T t) where T : SomeClassOrInterface{ // Code }

According to Microsoft's Documentation (It's one of the examples at the bottom of the page)

EDIT: If you want to return an object of type T, it's something like this

public T Whatever<T>(string values)
{  
    return /* code to convert the setting to T... */
}

In this case, you can check more details in this question

Alex Coronas
  • 468
  • 1
  • 6
  • 21