FormatWith icon indicating copy to clipboard operation
FormatWith copied to clipboard

Nested arguments

Open chibicitiberiu opened this issue 4 years ago • 4 comments

Does this library support nested arguments? i.e.:

"{foo.bar}".FormatWith(new { foo = new { bar = "test" } })

chibicitiberiu avatar Jan 04 '21 16:01 chibicitiberiu

Yep, basic sub-property traversal is supported. Your example will work and produce the string "test".

For implementation details, it was implemented in this PR: https://github.com/crozone/FormatWith/pull/13/commits

Note that array syntax is currently unsupported, i.e you cannot write "{foo.bar[0]}".FormatWith(new { foo = new { bar = new string[] {"test"} } }).

crozone avatar Jan 06 '21 17:01 crozone

Great, initially I tried it with a dictionary and it didn't work, so I thought it isn't supported. But after trying with an anonymous object it seems to work fine.

chibicitiberiu avatar Jan 06 '21 19:01 chibicitiberiu

@chibicitiberiu what dictionary format/layout did you try? If that was your first intuition when using the library, it will very likely be others as well, I could look at supporting it in the future.

crozone avatar Jan 12 '21 23:01 crozone

I tested several scenarios, and here is what I found:

// Scenario 1: works as expected, output is "test"
Debug.WriteLine("{foo.bar}".FormatWith(new 
{ 
    foo = new { bar = "test" }
}));

// Scenario 2 - object that contains a dictionary
// Doesn't work, throws KeyNotFoundException: The parameter "foo.bar" was not present in the lookup dictionary
Debug.WriteLine("{foo.bar}".FormatWith(new
{
    foo = new Dictionary<string, string>() { {"bar", "test" } }
}));

// Scenario 3 - dictionary that contains objects
// Doesn't work, throws KeyNotFoundException: The parameter "foo.bar" was not present in the lookup dictionary
Debug.WriteLine("{foo.bar}".FormatWith(new Dictionary<string, object>()
{
    { "foo", new { bar = "test" } }
}));

// Scenario 4 - nested dictionaries
// Doesn't work, throws KeyNotFoundException: The parameter "foo.bar" was not present in the lookup dictionary
Debug.WriteLine("{foo.bar}".FormatWith(new Dictionary<string, object>()
{
    { "foo", new Dictionary<string, string>() { { "bar", "test" } } }
}));

Other than the object-inside-object scenario, none of them worked as I might have expected. My use case is to actually have the user provide a pattern string, and having users be able to access some variables, like this:

Debug.WriteLine("{env.PATH}".FormatWith(new
{
    env = Environment.GetEnvironmentVariables(),
    // ... other vars ...
}));

// or 

Debug.WriteLine("{env.PATH}".FormatWith(new Dictionary<string, object>()
{
    { "env", Environment.GetEnvironmentVariables() },
    // ... other vars ...
}));

chibicitiberiu avatar Jan 13 '21 12:01 chibicitiberiu