Reputation: 3
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.
Upvotes: 0
Views: 55
Reputation: 32276
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;
}
}
Upvotes: 3