Skip to content

Add support for indexers (support for Arrays/Lists/Dictionaries/etc) #26

@crozone

Description

@crozone

At present, FormatWith supports basic property navigations in parameter keys. However, it does not support combining this with indexers to navigate into objects arrays, lists, or dictionaries.

For example, this is currently supported:

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

However, we should be able to do this:

string result = "{foo[\"bar\"].Length}".FormatWith(new 
{
    foo = new Dictionary<string, string> { ["bar"] = "test" }
});

This is the code that will need to be changed:

private static bool TryGetPropertyFromObject(string key, object replacementObject, out object value)
{
// need to split this into accessors so we can traverse nested objects
var members = key.Split(new[] { "." }, StringSplitOptions.None);
if (members.Length == 1)
{
PropertyInfo propertyInfo = replacementObject.GetType().GetProperty(key, propertyBindingFlags);
if (propertyInfo == null)
{
value = null;
return false;
}
else
{
value = propertyInfo.GetValue(replacementObject);
return true;
}
}
else
{
object currentObject = replacementObject;
foreach (var member in members)
{
PropertyInfo propertyInfo = currentObject.GetType().GetProperty(member, propertyBindingFlags);
if (propertyInfo == null)
{
value = null;
return false;
}
else
{
currentObject = propertyInfo.GetValue(currentObject);
}
}
value = currentObject;
return true;
}
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions