Bassie
Bassie

Reputation: 10390

How to return string value depending on type of generic

I have this code to get a list of Star Wars API objects:

public static async Task<IList<T>> Get<T>() 
    where T : SWAPIEntity
{
    var entities = new List<T>();
    var rootUrl = (string)typeof(T).GetProperty("rootUrl").GetValue(null);

    var url = $"{baseUrl}/{rootUrl}";

    var result = await GetResult<T>(url);
    entities.AddRange(result.results);

    while (result.next != null)
    {
        result = await GetResult<T>(result.next);
        entities.AddRange(result.results);
    }

    return entities;
}

Where I want rootUrl to depend on which type of SWAPIEntity is being passed in for T.

The code above throws

"Non-static method requires a target."

Where SWAPIEntity:

public class SWAPIEntity 
{
    public string name { get; }
}

and SWAPIEntity:

public class SWAPIEntity 
{
    public string name { get; }
}

and Planet:

public class Planet : SWAPIEntity
{
    public string rootUrl { get; } = "planets";

    public string climate { get; set; }
}

And I call it with

await StarWarsApi.Get<Planet>();

How can I get the value of rootUrl depending on which type of SWAPIEntity I am trying to get?

Upvotes: 1

Views: 90

Answers (1)

Ofir Winegarten
Ofir Winegarten

Reputation: 9365

The error says it all.

You are trying to call a non-static member, so you need to pass an Instance. I guess the simple solution for you is to make this property static.

public class Planet : SWAPIEntity
{
    public static string rootUrl { get; } = "planets";
    // Or newer simpler syntax:
    // public static string rootUrl => "planets";
    public string climate { get; set; }
}

Upvotes: 3

Related Questions