Verifying parent type on generic object

  • Thread starter Thread starter Kevin
  • Start date Start date
K

Kevin

If I had the following variables defined:

System.Collections.Generic.BindingList<String> obj1;
System.Collections.Generic.BindingList<Int32> obj2;

And then I wanted to tell if an object was any type of generic
BindingList what would the syntax be? I can get it to work with
non-generic types, but can't seem to get the statement to return back
true for both obj1 and obj2. Something like the following doesn't work:

if (obj1 is System.Collections.Generic.BindingList<object>) ...

Thanks.
 
if (obj1 is System.Collections.Generic.BindingList<object>) ...

Try this

Type t = obj1.GetType();
if (t.IsGenericType && t.GetGenericTypeDefinition() ==
typeof(BindingList<>))


Mattias
 
That worked great. Thank you. Now that I know the object is a type of
BindingList is there a way to write a generic routine to use an
enumerator to loop through whatever type of BindingList was found
regardless of the generic parameter type? Casting it something like:

System.Collections.Generic.BindingList<object> list =
(System.Collections.Generic.BindingList<object>)obj;

doesn't work. Thanks again.

Kevin
 
Now that I know the object is a type of
BindingList is there a way to write a generic routine to use an
enumerator to loop through whatever type of BindingList was found
regardless of the generic parameter type?

Sure, BingingList implements IEnumerable so you can use a foreach
loop.


Mattias
 
Back
Top