Lacutas
Lacutas

Reputation: 1

Return List of type implemented class

I am having some problems refactoring some code that returns JSON data from a web service. I've developed a base class as shown below, but this means I have to pass in the type to the GetList method. What I really need is it to automatically pick up the type of the derived class but I can't get it to work.

public abstract class LocalSystemTable
{
    public abstract string TableName { get; }
    public abstract string SingularName { get; }

    public List<T> GetList<T>(string baseUri, UserCredentials userCredentials)
    {
        var response = RestClient.At(baseUri).WithContentType(ContentType.Json).For(userCredentials).Get<dynamic>();

        var result = (response.ResponseObject[TableName])[SingularName];
        bool isArray = result.GetType() == typeof(JArray);

        if (isArray)
            return result.ToObject<List<T>>();
        else
        {
            T single = result.ToObject<T>();
            return new List<T> { single };
        }
    }
}

Basically I want to turn this:

GiftAidSettings settings = new GiftAidSettings();
List<GiftAidSettings> results = settings.GetList<GiftAidSettings>("some_uri", userCredentials);

Into this:

GiftAidSettings settings = new GiftAidSettings();
List<GiftAidSettings> results = settings.GetList("some_uri", userCredentials);

Is that possible?

Thanks

Upvotes: 0

Views: 71

Answers (1)

Arie
Arie

Reputation: 5373

I dont know if this is what you want, but you can do something like this:

    public abstract class BaseClass<T>
        where T : BaseClass<T>, new()
    {
        public List<T> GetList(string someParameter)
        {
            return new List<T>() { new T() };
        }
    }

    public class BaseClassImplementation : BaseClass<BaseClassImplementation>
    {
        // ..............
    }

then:

    BaseClassImplementation n = new BaseClassImplementation();
    List<BaseClassImplementation> l = n.GetList("some parameter");

Upvotes: 1

Related Questions