0

I have a base class BaseRepository which other classes extend.

public class BaseRepository
{
    protected RestClient client;
    protected string url;

    public BaseRepository ()
    {
        client = RestClient.GetInstance ();
    }

    public async Task<T> Find<T> (string id) {
        dynamic response = await client.Find(url, id);

        return DeserializeItem<T> (response);
    }
}

and then I have a UsersRepository class which extends from the base class.

public class UsersRepository : BaseRepository
{
    string url = "users";
    static UsersRepository instance;

    private UsersRepository ()
    {
    }

    public static UsersRepository GetInstance() {
        if (instance == null) {
            instance = new UsersRepository ();
        }

        return instance;
    }
}

I can't figure out how to pass User as the response type for the public async Task<T> Find<T> (string id) method. I could create this method in the UsersRepository but I do not want to duplicate the code.

public override function User Find(string id) {
    return base.Find<User>(id);
}

Any help would be much appreciated.

1 Answer 1

3

It looks like you actually want the generic type defined on the base class and not the method. Also I think you want to set the url defined in the base class in the constructor of the derived class.

public class BaseRepository<T>
{
    protected RestClient client;
    protected string url;

    public BaseRepository ()
    {
        client = RestClient.GetInstance ();
    }

    public async Task<T> Find(string id) {
        dynamic response = await client.Find(url, id);

        return DeserializeItem<T> (response);
    }
}

public class UsersRepository : BaseRepository<User>
{
    static UsersRepository instance;

    private UsersRepository ()
    {
        url = "users";
    }

    public static UsersRepository GetInstance() {
        if (instance == null) {
            instance = new UsersRepository ();
        }

        return instance;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.