FormatWith
FormatWith copied to clipboard
Nested arguments
Does this library support nested arguments? i.e.:
"{foo.bar}".FormatWith(new { foo = new { bar = "test" } })
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"} } }).
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 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.
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 ...
}));