How to pass and traverse an anonymous object in a method

1

How can I pass an anonymous object to a method, and then traverse it?

What I'm trying to do is the following:

public static string QueryStringToUrl(string url, Dictionary<string, string> query)
{
    var uriBuilder = new UriBuilder(url);
    var queryString = HttpUtility.ParseQueryString(uriBuilder.Query);

    // Aqui o objeto anônimo seria percorrido e então adicionaria
    // um novo parâmetro para a QueryString da URL AO INVÉS do dicionário.
    foreach (var q in query)
    {
        queryString[q.Key] = q.Value;
    }

    uriBuilder.Query = query.ToString();

    return uriBuilder.ToString();
}

And I'm calling it like this:

QueryStringToUrl("http://example.com/?param1=abc", new Dictionary<string, string>
{
    { "param2", "12345" },
    { "otherParam", "huehue" }
});
// URL passada -> http://example.com/?param1=abc
// URL retorno -> http://example.com/?param1=abc&param2=12345&otherParam=huehue

But I wish it were like this:

QueryStringToUrl("http://example.com/?param1=abc", new
{
    param2 = 12345,
    otherParam = "huehuehue"
});
// URL passada -> http://example.com/?param1=abc
// URL retorno -> http://example.com/?param1=abc&param2=12345&otherParam=huehue
  

Example of similar use with Jil to serialize in JSON:

JSON.Serialize(new
{
    param2 = 12345,
    otherParam = "huehuehue"
})

Output:

{"param2":"12345","otherParam":"huehuehue"}

Jil on GitHub :

I met Jil here . At the bottom of the " Programming Stack " page

    
asked by anonymous 21.01.2018 / 19:30

1 answer

1

It is possible to use reflection, but I do not recommend it, it saves typing but loses speed and can create maintenance difficulties. Jil does this, but in a more performative way.

Note that the example where it was used has a generic method .

I'd rather use (param2 : 12345, otherParam : "huehuehue") . But creating a type is better. It should also work with a type dynamic , although rarely is it necessary , even though people think it is, but what should perform best is Dictionary itself.

The following code works for everyone.

using static System.Console;

public class Program {
    public static void Main() => Teste(new { param2 = 12345, otherParam = "huehuehue" });
    public static void Teste<T>(T param){
        foreach (var item in typeof(T).GetProperties()) WriteLine($"{item.Name} : {item.GetValue(param, null)}");
    }
}
    
21.01.2018 / 21:45