0

Currently I'm working on an web-API dependent application. I have made a class with a lot of API strings like: /api/lol/static-data/{region}/v1/champion/{id}. Also I made a method:

public static String request(String type, Object[] param)
{
    return "";
}

This is going to do the requesting stuff. Because it's very different with each request type how many parameters are being used, I'm using an array for this. Now the question is, is it posssible to String.Format using an array for the paramaters while the keys in the strings are not numbers? Or does anyone know how to do this in a different way?

2
  • I suggest you change your title to "using strings instead of numbers as format specifiers" or something similar - this isn't really about arrays...
    – Jon Skeet
    Commented Feb 5, 2014 at 9:03
  • It's also unclear how you want to map your inputs to the relevant keys.
    – Jon Skeet
    Commented Feb 5, 2014 at 9:04

1 Answer 1

2

No, string.Format only supports index-based parameter specifications.

This:

"/api/lol/static-data/{region}/v1/champion/{id}"
                      ^^^^^^^^             ^^^^

will have to be handled using a different method, like string.Replace or a Regex.

You will need to:

  • Decide on the appropriate method for doing the replacements
  • Decide how an array with index-based values should map to the parameters, are they positional? ie. {region} is the first element of the array, {id} is the second, etc.?

Here is a simple LINQPad program that demonstrates how I would do it (though I would add a bit more error handling, maybe caching of the reflection info if this is executed a lot, some unit-tests, etc.):

void Main()
{
    string input = "/api/lol/static-data/{region}/v1/champion/{id}";
    string output = ReplaceArguments(input, new
    {
        region = "Europe",
        id = 42
    });
    output.Dump();
}

public static string ReplaceArguments(string input, object arguments)
{
    if (arguments == null || input == null)
        return input;

    var argumentsType = arguments.GetType();
    var re = new Regex(@"\{(?<name>[^}]+)\}");
    return re.Replace(input, match =>
    {
        var pi = argumentsType.GetProperty(match.Groups["name"].Value);
        if (pi == null)
            return match.Value;

        return (pi.GetValue(arguments) ?? string.Empty).ToString();
    });
}
1
  • That's a very nice method. This will do the job. I will add your credits to the source! Commented Feb 5, 2014 at 9:19

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.