How to pass a class reference to a generic type parameter?

126 Views Asked by At

I want to pass the reference of the same class to the GetInquiry class dynamically that I would to MyClass.

public class MyClass<T> where T: class
{
    public T Inquiry(T obj)
    {
         string Username = "myUser";

         Task<MyClass<T>> myTask = GetInquiry<MyClass<T>>.Inquire(Username); //Want to pass the same class reference passed in MyClass<T>
         obj = myTask.Result; //gives error of implicit conversion
         return obj;
    }
}
public static class GetInquiry<T> where T: class
{
    public static async Task<T> Inquire(string Username)
    {
        //some code
    }
}

So, when I pass any class to MyClass, its reference should also be passed to down to the GetInquiry class at runtime, but I end up getting error instead that it cannot implicitly convert the types. Workarounds are also appreciated.

1

There are 1 best solutions below

0
Selmir Aljic On

The problem is that public T Inquiry(T obj) method is trying to return T, but in the code you are not assigning T to obj you are trying to assign MyClass<T> to obj

public class MyClass<T> where T: class
{
    public T Inquiry(T obj)
    {
        string Username = "myUser";

         Task<MyClass<T>> myTask = GetInquiry<MyClass<T>>.Inquire(Username);
         obj = myTask.Result; // (Result here is MyClass<T> and not T, so you can't assign it to T obj)
         return obj;
    }
}

Depending on your use case this can be solved in a lot of different ways, you can change the GetInquiry<MyClass<T>>.Inquire(Username) to GetInquiry<T>.Inquiry(Username), you can change the MyClass<T>.Inquiry() return type from T to MyClass<T>.

What the right approach is depends entirily on your usecase and design.