Generics and Reflection

  • Thread starter Thread starter Chris McKenzie
  • Start date Start date
C

Chris McKenzie

I have a situation in which I need to test to see if an object implements a
Generic Interface. My collection contains objects which do not implement the
interface, and objects that implement the Generic Interface with different
Generic arguments. I don't care what the specific arguments are to the
Generic Interfaces.

Example:
I have a Generic Interface:
interface IMyGenericInterface<T>
{
void DoSomethingSpecial();
}

And an object collection that contains the following objects:

(0) Sytem.Object
(1) IMyGenericInterface<string>
(2) IMyGenericInterface<int>

For a specified index, I need to know if the object implements
IMyGenericInterface so that I can call DoSomethingSpecial, however, I don't
know ahead of time what Types may be used for <T>.

Anyone know how I can do this?
Thanks,
Chris McKenzie
http://weblogs.asp.net/taganov
 
Chris McKenzie said:
I have a situation in which I need to test to see if an object implements a
Generic Interface. My collection contains objects which do not implement the
interface, and objects that implement the Generic Interface with different
Generic arguments. I don't care what the specific arguments are to the
Generic Interfaces.

Example:
I have a Generic Interface:
interface IMyGenericInterface<T>
{
void DoSomethingSpecial();
}

And an object collection that contains the following objects:

(0) Sytem.Object
(1) IMyGenericInterface<string>
(2) IMyGenericInterface<int>

For a specified index, I need to know if the object implements
IMyGenericInterface so that I can call DoSomethingSpecial, however, I don't
know ahead of time what Types may be used for <T>.

Hello,
The following code will illustrate how to do that.

using System;
using System.Collections.Generic;

class GenericInterface {

// As an example, I'll use IComparable<T>
void LookForGenericInterface() {
foreach (object item in list) {
foreach (Type type in item.GetType().GetInterfaces())
if (type.IsGenericType) {
// the interface is generic
Type def = type.GetGenericTypeDefinition();
// note the use of <> to get the definition
if (def == typeof(IComparable<>))
Do(item, type, type.GetGenericArguments()[0]);
}
}
}

void Do(object value, Type interfaceType, Type typeParameter) {
// value:
// The instance
// interfaceType:
// The type of the interface e.g. IComparable<string>
// typeParameter:
// The type of the type parameter e.g. string
}

static IList<object> list;
}


HTH,
Mark
 

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

Back
Top