generics and reflection

P

parez

Hi

One of the property of returnedObject is of the type List<MyClass> (in
just one instance)
in some other case it could be List<MyClass2>

I want to check if a particular propert is a generic list.
If it is, then do something with the type of the the class (MyClass
and MyClass2)


PropertyInfo[] propertyInfo =
returnedObject.GetType().GetProperties();

foreach (PropertyInfo pi in propertyInfo)
{

// one of the "pi"s is of the list List<MyClass>
if (pi.PropertyType == typeof(List<>))
{
//Do Speical stuff

how do i go about this..
 
J

Jon Skeet [C# MVP]

parez said:
One of the property of returnedObject is of the type List<MyClass> (in
just one instance)
in some other case it could be List<MyClass2>

I want to check if a particular propert is a generic list.
If it is, then do something with the type of the the class (MyClass
and MyClass2)


PropertyInfo[] propertyInfo =
returnedObject.GetType().GetProperties();

foreach (PropertyInfo pi in propertyInfo)
{

// one of the "pi"s is of the list List<MyClass>
if (pi.PropertyType == typeof(List<>))
{
//Do Speical stuff

how do i go about this..

Take pi.PropertyType, then:

o Check it's generic: type.IsGeneric
o Get the generic type: type.GetGenericType
o Check whether that generic type is List<>
o Fetch the generic type argument: type.GetGenericArguments

That's entirely untested, but I think it should work...
 
P

parez

parez said:
One of the property of returnedObject is of the type List<MyClass> (in
just one instance)
in some other case it could be List<MyClass2>
I want to check if a particular propert is a generic list.
If it is, then do something with the type of the the class (MyClass
and MyClass2)
PropertyInfo[] propertyInfo =
returnedObject.GetType().GetProperties();
foreach (PropertyInfo pi in propertyInfo)
{
// one of the "pi"s is of the list List<MyClass>
if (pi.PropertyType == typeof(List<>))
{
//Do Speical stuff
how do i go about this..

Take pi.PropertyType, then:

o Check it's generic: type.IsGeneric
o Get the generic type: type.GetGenericType
o Check whether that generic type is List<>
o Fetch the generic type argument: type.GetGenericArguments

That's entirely untested, but I think it should work...

Thanks..

This is what worked for me.


if (pi.PropertyType.IsGenericType)
{

if (pi.PropertyType.GetGenericTypeDefinition() ==
typeof(List<>))
{
// pi.PropertyType.GetGenericArguments() is
MyClass2, MyClass
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top