Search code examples
c#.netgenericsinterfaceoverriding

Generic method "hides" non-generic one when calling


I am trying to call a method on an object that implements these two methods:

        public async Task<ServiceRequest> GetByIdAsync(int id)
        {
            return await _context.ServiceRequests
                .Include(sReq => sReq.ServiceResponse)
                .SingleOrDefaultAsync(c => c.ServiceRequestId == id);
        }

        public async Task<ServiceRequest?> GetByIdAsync<TId>(TId id, CancellationToken cancellationToken = default) where TId : notnull
        {
            throw new NotImplementedException();
        }

The first method is from the interface IRepository<T> : IBaseRepository<T>

The second is from the extended interface IBaseRepository<T>

I am calling a method like this:

ServiceRequest sr = await _sReqRepo.GetByIdAsync(serviceRequestId);

It hits the second method and throws the NotImplementedException

Is there a way to explicitly call the first method?

I tried to explicitly call a method using interface variable like this:

IRepository<ServiceRequest> serviceRequestRepository = _sReqRepo;
ServiceRequest sr = await serviceRequestRepository.GetByIdAsync(serviceRequestId);

but it hits the the second method still.


Solution

  • As poeple pointed out in comments, it turned out the serviceRequestId was a string, that's why it was calling generic version of the method.