How to pass a generic type parameter reference to a function in C#?

651 Views Asked by At

I am trying to create a generic function which accepts any type of object and return it after the inquiry. However, the method I am creating is calling another generic function, which also accepts any type of object, but in my case I want to reference the class/type of "obj" to the GetInquiry() function in order for it to run, but according to this design, I won't be knowing its type at compile time, hence I am unable to call the GetInquiry() function.

public T Inquiry<T>(T obj)
{
    string Username = "myUser";
    Task<T> myTask = Inquire<T>.GetInquiry(Username); //throws 'T' must be a reference type
    obj = myTask.Result;
    return obj;
}
public static class Inquire<T> where T: class
{
    public static async Task<T> GetInquiry(string Username)
    {
        //some code
    }
}

How am I supposed to pass the reference? Any other workarounds and refactoring suggestions are also appreciated.

2

There are 2 best solutions below

0
Rufus L On

"the method I am creating is calling another generic function, which also accepts any type of object"

This statement is not correct...the method you're calling does NOT accept any type of object; it only accepts objects which are classes. In order for you to pass your type to it, you need to apply the same constraint:

public T Inquiry<T>(T obj) where T: class
{
    string Username = "myUser";
    Task<T> myTask = Inquire<T>.GetInquiry(Username); //throws 'T' must be a reference type
    obj = myTask.Result;
    return obj;
}
0
M.Othman On
public static class Inquire<T>
{
    public static Task<T> GetInquiry(string username)
    {
        //run process
        Task<T> result = new Task<T>(() => {
            //do something
        });
        return result;
    }
}

The easiest way to solve this problem is to make the Inquiry method generic, like this:

public T Inquiry<T>(T obj) 
    where T : class
{
    string Username = "myUser";
    Task<T> myTask = Inquire<T>.GetInquiry(Username);
    obj = myTask.Result;
    return obj;
}

This way, you can specify the type parameter T to be a reference type, which will allow you to call the GetInquiry() method without any errors.