Skip to content

Instantly share code, notes, and snippets.

@enisn
Last active August 2, 2022 07:43
Show Gist options
  • Save enisn/aa07da19858c303454febf320b4f1890 to your computer and use it in GitHub Desktop.
Save enisn/aa07da19858c303454febf320b4f1890 to your computer and use it in GitHub Desktop.
Challenge #2 - Solution - GetPropValue
public static object GetPropValue(this object obj, string name)
{
if (obj == null)
{
return null;
}
foreach (string part in name.Split('.'))
{
if (obj.IsNonStringEnumerable())
{
var toEnumerable = (IEnumerable)obj;
var iterator = toEnumerable.GetEnumerator();
if (!iterator.MoveNext())
{
return null;
}
obj = iterator.Current;
}
Type type = obj.GetType();
PropertyInfo info = type.GetProperty(part);
if (info == null) { return null; }
obj = info.GetValue(obj, null);
}
return obj;
}
private static bool IsNonStringEnumerable(this object instance)
{
return instance != null && instance.GetType().IsNonStringEnumerable();
}
private static bool IsNonStringEnumerable(this Type type)
{
if (type == null || type == typeof(string))
return false;
return typeof(IEnumerable).IsAssignableFrom(type);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment