I need a way to convert the properties of an object of type T to objects of the property type, and values as they are in T. My reason for doing this is so that I can check if the property is or inherits from IEnumerable (Lists, arrays, etc.), and if it does then I need to pass that IEnumerable as an object to be worked on. So far I have
foreach (var propInfo in obj.GetType().GetProperties())
{
var newObject = Activator.CreateInstance(propInfo.PropertyType, propInfo.GetValue(obj));
if (ObjectProcessing.ImplementsIEnumerable(newObject))
{
ObjectProcessing.ObjectQueue.Enqueue(newObject);
}
}
Which unfortunately doesn't work. I cant use CreatInstance<T>
because it seems the compiler assumes T is the T in the method signature, which is the source object not the target object.
The question looks like a XY problem. What is the XY Problem?
You do not need to create an instance of the object to see if it implements or is IEnumerable
. Let me build upon what you have so far
// This is the example object
public class MyClass {
public IEnumerable A{ get;set;}
public List<int> B{get;set;}
}
var myClass = new MyClass();
foreach (var propInfo in myClass.GetType().GetProperties()) {
var typeOfProperty = propInfo.PropertyType;
var isIEnuerableOrInheritingFromIt = typeof(IEnumerable).IsAssignableFrom(typeOfProperty);
if (isIEnuerableOrInheritingFromIt) {
var objectThatImplementsIEnumerable = propInfo.GetValue(myClass);
// Do stuff with it
}
}