Reputation: 4198
I am having a methong that gets values of properties or gets values of nested properties, this part is working fine but I wanted to add collection to string in case some property is a collection and i seem to have a problem with that:
Code:
public static object GetNestedPropValue<TObject>(TObject obj, string propName)
{
string[] nestedObjectProp = propName.Split('.');
string[] childProperties = nestedObjectProp.Skip(1).ToArray();
string parentProp = nestedObjectProp.FirstOrDefault();
foreach (string property in childProperties)
{
if (obj == null)
{
return null;
}
PropertyInfo info = obj.GetType().GetProperty(parentProp);
if (info == null)
{
return null;
}
object nestedObject = info.GetValue(obj);
if(childProperties.Count() == 1)
{
Type checkNestedType = nestedObject.GetType();
if (IsICollection(checkNestedType) && IsIEnumerable(checkNestedType))
{
var nestedObjectValues = nestedObject as List<object>;
return string.Join(", ", nestedObjectValues
.Select(i => i.GetType().GetProperty(childProperties.FirstOrDefault()).GetValue(nestedObject))
.ToArray());
}
return nestedObject.GetType().GetProperty(childProperties.FirstOrDefault()).GetValue(nestedObject);
}
GetNestedPropValue(nestedObject, string.Join(".", childProperties.Skip(1)));
}
return null;
}
problem is here:
var nestedObjectValues = nestedObject as List<object>;
return string.Join(", ", nestedObjectValues
.Select(i => i.GetType().GetProperty(childProperties.FirstOrDefault()).GetValue(nestedObject))
.ToArray());
When I try to type to list of object it gives me null, what seems to be the problem?
Upvotes: 0
Views: 110
Reputation: 4744
nestedObject
is simply NOT a List<object>
, so nestedObject as List<object>
returns null.
Being a collection type and being enumerable certainly doesn't mean the type is List<T>
for some T. And even then, a List<T>
is not directly castable to a List<object>
anyway (except obviously if T is object
).
I'm not sure what you're trying to achieve here, but inspecting types through reflection before trying to cast objects to a loose guessed type feels very weird to me.
Upvotes: 2