Reputation: 596
I have this in these classes.
public class MyClass:BaseClass
{ }
public class BaseClass
{ }
public class CollectionClass
{
public string SomeProperty {get; set;}
public List<MyClass> Collection {get; set;}
}
In my code I want to find out if the property in some object (e. g. CollectionClass
) is a type of List<BaseClass>
also I want to return true if the property is a type of List<MyClass>
. The code below explains that.
public bool ContainsMyCollection(object obj)
{
foreach(var property in obj.GetType().GetProperties())
{
// Idk how to accomplish that
if(property isTypeof List<BaseClass>)
return true;
}
return false
}
Upvotes: 1
Views: 97
Reputation: 38727
You need to check if you have a closed type of List<>
. This can be done like so:
if(property.PropertyType.IsGenericType
&& property.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
and then you have to check if the generic argument (the T
part of List<T>
) is assignable to your base type:
if (typeof(BaseClass).IsAssignableFrom(property.PropertyType.GetGenericArguments()[0]))
Putting that together, you get this:
public bool ContainsMyCollection(object obj)
{
foreach(var property in obj.GetType().GetProperties())
{
// Idk how to accomplish that
if(property.PropertyType.IsGenericType
&& property.PropertyType.GetGenericTypeDefinition() == typeof(List<>)
&& typeof(BaseClass).IsAssignableFrom(property.PropertyType.GetGenericArguments()[0]))
{
return true;
}
}
return false;
}
Note that, as explained in the comments, List<MyClass>
isn't derived from List<BaseClass>
, even if MyClass
is derived from BaseClass
. So, for example, List<BaseClass> a = new List<MyClass>();
will fail. That falls outside the scope of your question, but I figured I'd give you the heads up in case you didn't already know.
Upvotes: 2