Override virtual generic method

86 Views Asked by At

I have a generic method like this:

public class DomainServiceBase<TEntity> : IDomainServiceBase<TEntity> where TEntity : class
{
    public virtual async Task<bool> InsertAndSaveAsync<TRequest>(TRequest request)
    {
        // Implementations
    }
}

And i override it in another class like this:

public class AnnouncementDomainService : DomainServiceBase<AnnouncementDataModel>, IAnnouncementDomainService
{
    public override async Task<bool> InsertAndSaveAsync<AnnouncementAddRequest>(AnnouncementAddRequest request)
    {
        // an example of my issue
        var title =  request.Title // here i get CS1061 error

        // Implementations
    }
}

I do not have any access to AnnouncementAddRequest properties.

This is AnnouncementAddRequest model :

    public class AnnouncementAddRequest
    {
        public string Title { get; set; }
        public string Code { get; set; }
        public string? Description { get; set; }
        public bool IsActive { get; set; }
        public AnnouncementAddRequest()
        {
            Title = string.Empty;
            Code = string.Empty;
        }
    }

As you can see, all properties are public I attach a screenshot from visual studio intelliSense

enter image description here

I am trying to override virtual generic method in the derived class so I can do validations and at the end, execute await base.InsertAndSaveAsync(request)

1

There are 1 best solutions below

0
Michał Turczyn On

Your problem is that if you specify the method with generic parameters, if you override it in inheriting class, you must keep generic type parameter.

Source of your confusion lies in overriding method declaration, where you have specified:

public override async Task<bool> InsertAndSaveAsync<AnnouncementAddRequest>(
    AnnouncementAddRequest request) { ... }

Compiler treats AnnouncementAddRequest as just another "name" for generic parameter, but it is still generic param, just as T or whatever. It's not your class.

Now, once we explained where the problem is, the solution is to add this parameter as generic parameter to your base class, as already mentioned in the other answer.