0

I'm writing some code that should update some fields with a common logic on different remote objects. Therefore I use given API. The Test Class is my own implementation. The other two classes are given by the API. When I write the following code i get the error

The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'QueryAPI.Query<T>()

Code:

 public class Test<T> where T : class, UnicontaBaseEntity
    {
        private async Task Foo<T>(QueryAPI queryAPI, CrudAPI crudAPI, SyncSettings syncSettings)
        {
            Task<T[]> result = await queryAPI.Query<T>();
        }
    }

    public interface UnicontaBaseEntity : UnicontaStreamableEntity
    {
        int CompanyId { get; }

        Type BaseEntityType();
    }


    public class QueryAPI : BaseAPI
    {
        ...
        public Task<T[]> Query<T>() where T : class, UnicontaBaseEntity, new();
        ...
    }

Any ideas on this?

Thanks in advance.

KR Mike

coder
  • 8,346
  • 16
  • 39
  • 53
  • `Test` -> `Foo` doesn't make sense. Since the class is generic, make the method non generic. – Ivan Stoev Apr 23 '18 at 08:28
  • 1
    The compiler even generates a warning for that. The `T` withint the scope of the `Foo` method hides the `T` of the `Test` class. – Dirk Apr 23 '18 at 08:31
  • Possible duplicate of [The type must be a reference type in order to use it as parameter 'T' in the generic type or method](https://stackoverflow.com/questions/6451120/the-type-must-be-a-reference-type-in-order-to-use-it-as-parameter-t-in-the-gen) – trailmax Apr 23 '18 at 09:02

1 Answers1

0

I would remove T from Foo() here since your parent class Test<T> is already generic.

You should also add a new() constraint otherwise there will be another error since QueryAPI expects a type with default constructor.

Also, some renames to include Async are in order.

public class Test<T> where T : class, UnicontaBaseEntity, new()
{
    private async Task FooAsync(QueryAPI queryAPI, CrudAPI crudAPI, SyncSettings syncSettings)
    {
        Task<T[]> result = await queryAPI.QueryAsync<T>();
    }
}

public interface UnicontaBaseEntity : UnicontaStreamableEntity
{
    int CompanyId { get; }

    Type BaseEntityType();
}


public class QueryAPI : BaseAPI
{
    ...
    public Task<T[]> QueryAsync<T>() where T : class, UnicontaBaseEntity, new()
    ...
}
Tanveer Badar
  • 5,438
  • 2
  • 27
  • 32