C# and specialized generic method - how to implement it?

senglory 1 Reputation point
2022-05-12T20:59:33.623+00:00

Hi,
I'm trying to make a highly specialized version of generic method that my class inherits from its ancestor:

public class Request<K>
{
    public K Id;
}

public class Response<T>
{
    public T Data;
}

public class MyDto
{
}


public abstract class BaseStorage
{
    public virtual Response<T> GetDemo<T, K>(Request<K> request)
    {
    }
}


public class ChildStorage : BaseStorage
{
    public override Response<MyDto> GetDemo<MyDto, int>(Request<int> request)
    {
        return new Response<MyDto>();
    }
}

How should I write my specialized GetDemo() implementation w/o compiler errors?

Developer technologies | C#
{count} votes

2 answers

Sort by: Most helpful
  1. Jack J Jun 25,296 Reputation points
    2022-05-13T03:03:24.057+00:00

    @senglory , you could try the following code to implment the generic method from the abstract class without the compliler errors.

    public abstract class BaseStorage  
        {  
            public  abstract Response<T> GetDemo<T,K>(Request<K> request);  
        }  
      
      
        public class ChildStorage : BaseStorage  
        {  
            public override Response<T> GetDemo<T, K>(Request<K> request)  
            {  
               return new Response<T>();  
            }  
        }  
    

    You could call it like the following code:

        Request<int> request = new Request<int>();    
        request.Id = 1;  
        Response<MyDto> response = new Response<MyDto>();  
        response.Data = new MyDto { Name="test1" ,Description="d1"};  
        ChildStorage storage = new ChildStorage();  
        Response<MyDto> response1 = storage.GetDemo<MyDto, int>(request);  
    

    Hope this could help you.

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. senglory 1 Reputation point
    2022-05-19T12:26:56.2+00:00

    Also I found another solution:

    public abstract class BaseStorage<T, K>
    {
        public virtual Response<T> GetDemo(Request<K> request)
        {
            throw new NotImplementedException();
        }
    }
    
    
    public class ChildStorage : BaseStorage<MyDto, int>
    {
        public override Response<MyDto> GetDemo(Request<int> request)
        {
            return new Response<MyDto>();
        }
    }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.