473,850 Members | 2,073 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Test for generic interface

I have a problem formulating a test to see if an object is implementing
a generic interface.

I have the following:

public interface IGeneric<T>
void Foo();

public class StringClass : IGeneric<string >
public void Foo()
{/** something**/}

If i happen to get a hold of an object (which could be a StringClass),
how do i check if it implements the IGeneric<interf ace, and if it
does, how do i get a hold of the fact that the generic parameter is a

Thank you,

Nov 7 '06 #1
8 3919
Well, each usage creates a separate interface, and note that a class could
happily implement IGeneric<string and IGeneric<intand IGeneric<float> .

You can look at reflection (see below); however, note that (with a few
exceptions) in most circumstances you really want to check if it implements
a *specific* one (even if that is using a TSomething from another generic),
in which case you can just check if it is IGeneric<TSomet hing>.

Did you have a specific purpose in mind? This could yield a better answer...


using System;
class Program {
static void Main()
Demo obj = new Demo();
Type genericIDemoTyp e = typeof(IDemo<>) ;
foreach (Type interfaceType in obj.GetType().G etInterfaces())
if (interfaceType. IsGenericType)
Type test = interfaceType.G etGenericTypeDe finition();
if (test == genericIDemoTyp e)
Console.WriteLi ne("Supports IDemo<with type: " +
interfaceType.G etGenericArgume nts()[0].Name);
interface IDemo<T>
void SomeMethod(T param);
class Demo : IDemo<string>, IDemo<int>
public void SomeMethod(stri ng param)
public void SomeMethod(int param)
Nov 7 '06 #2
Hi Marc,

Thank you for the reply.

I am aware that a class could implement the interface more than once,
and in fact i am using this already.

The scenario is of course bigger than my one-class example.

I find it very usefull that i can "tag" a class with two pieces of
information with a generic interface at the same time very useful. I
can tag it with both the interface and the generic argument. I can put
this in a very readable and compact line.

I have considered using attributes for this tagging, but they do no
give me the ability to place a contract on the classes, as an interface
does. That is why i am sticking to interfaces so far.

My scenario is this:

At some point i create a user control. If this user control is
implementing a certain generic interface (IListener<Tor similar), it
means that this user control wants to be notified, when there are
updates to a certain part of datastore.

Let us say we have a user control implementing a IListener<Rates >, this
user control should after being created, be signed up by someone else
to the list of those who are interested in updates of the Rates.

The problem is that i cannot test any user control directly to see if
it implements the IListener<Rates >, as i have several hundred other
things to listen for. Besides Rates, we have Units, Customers,... and
the list goes on. I cannot loop to see if the usercontrol by chance
implements IListener<Maybe _this_BusinessO bject>, as it would simply
take too long.

My IListen<Thas a base (IListenBase), but that is just to speed up
the detection. It does not solve anything.

What i really need is a way to ask a more general question such as:

If( userControl is IListen<)

But i can only get away with writing the IListen<inside a typeof()

I managed to get the Rates type out of a IListen<Rates>, but that is
only the second half.


Nov 7 '06 #3
How about:

interface IListenBase
{} // leave empty so no implementation required
interface IListen<T: IListenBase
// actual members

Now you can check (the easy way) to see if something implements IListenBase,
and then (if they do), look at reflection to see which IListen<interfa ces
they support (as per my example).

Nov 7 '06 #4
Hi Marc,

Thank you again for replying.

I am sorry for changing the name of the interface by mistake, but let's
continue with the IListen<>.

As far as I can see, your suggestion is exactly what I have tried to
communicate with the

"My IListen<Thas a base (IListenBase), but that is just to speed up
the detection. It does not solve anything. "

part of the previous post.

I have an empty IListenBase as a base for the generic interface. Bu
that does not change anything. This is because of two things:

A) knowing that a class implements the IListenBase, does not tell me
what kind of IListen<it implements. It does not get me any closer to
the solution. As i wrote it speeds up the detection, as i can write
"if(compone nt is IListenBase)" and know if i am getting close, but it
does not tell me anything more.

B) There is no guard against some looney programmer might implement the
IListenBase, but not any actual IListen<interfa ce.

What I really need is some finer grained distinction in the C#
language/.Net platform, that can says:

"Yes, this object implements IListen<>' and "The argument to IListen<>
is Rates".

I realize that IListen<Custome rand IListen<Ratesar e two different
interfaces. But i am baffled by the fact that there seems to be no
simple way to test for the fact that there is a common denominator in
the IListen<generic interface.

If i say "Find all references" in Visual Studio 2005 on the name of the
generic interface, it finds all my implementations of IListen<>, no
matter what i have given as the generic argument.

I of course know that VS 2005 and the .Net platform is not the same,
but i am refering to the idea. Visual Studio is aware of the connection
between IListen<>, IListen<Ratesan d IListen<Custome rs>, where as the
C# language doesn't have any way of expressing that.

I am experimenting with the reflection part, looping through all the 32
interfaces my user controls are implementing, checking by string
comparison if any of the interfaces might contain some magic strings,
but that is slow and very inelegant.


Thank you for taking the time to answer,

Nov 8 '06 #5
OK - one thing at a time.

Re the IListen [I'll drop the Base for brevity] / IListen<T>, I was
suggesting using IListen as a marker only. If something implements
IListen<Tfor some T then it *must* implement IListen, so you can use "does
it implement IListen" as a quick first stab. Then only *if* it implements
IListen do you look at reflection, under the assumption that it could have
0, 1 or many IListen<Timplem entations.

Re checking with strings... don't do that. I posted demo code in my first
example that identified the exact generic types of IListen<Twithou t
reverting to anything that ugly. If necessary, you can also use
MakeGenericMeth od to then switch (via reflection) to proper typed (generic)
code - for instance you could have a method as below; you can get the
generic method via reflection, and call MakeGenericMeth od using the Type
found previously to make and invoke the *real* code. Then when you Invoke()
it, it will (after passing the objects) be running in nicely compiled code

void HookListener<T> (IListen<Tsourc e) where T : new() {
// do some interesting things involving T and source

Nov 8 '06 #6
I think I see things more clearly now. The things I was experimenting
with is going in the same direction as your first example. I will stick
to your example and loose the string comparison.

Regarding the first quick stab, I think we are talking about the same
thing. At this point I don't think I will implement such an
optimization just yet, but it is an obvious optimization. I think there
might be a risk of someone implementing the non-generic interface,
without the generic one. I like defensive programming.

The "Sigh" in my previous post was about the fact that we need to
resort to reflection. I would have liked to see a
language-kind-of-contruct do it for me. After all we got a nice "is"
operator. It would be more elegant if it could handle a generic
interface without a type argument. Wether or not it would end up in
reflection behind the curtains anyway, is less important. I am sure the
..Net guys' implementation is faster than mine anyway.

THank you for your help.
- Kasper

Nov 8 '06 #7
One other thought... it occurred to me that of course you don't need to use
MakeGenericMeth od at all... once you have the Type of the interface, that
you know is a closed form of IListen<>, then you can just obtain and invoke
the MethodInfo via reflection, which will *be* the generic method.

But yes... generics are only directly useful in their intended form when the
system can figure out the closed type.

Nov 8 '06 #8
I like the way of thinking of the interface as an open or closed form.
That makes sense to me.

I think line 9-12 in your first example nails the question i had. First
a check to see if it is generic, and the a check to see of it has the
same "definition ". I was lacking a way to formulate a comparison of the
"definition ". Too bad we have to loop and all, but it is acceptable.

Thank you,

Nov 8 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

by: Andreas Huber | last post by:
What follows is a discussion of my experience with .NET generics & the ..NET framework (as implemented in the Visual Studio 2005 Beta 1), which leads to questions as to why certain things are the way they are. ***** Summary & Questions ***** In a nutshell, the current .NET generics & .NET framework make it sometimes difficult or even impossible to write truly generic code. For example, it seems to be impossible to write a truly generic
by: KH | last post by:
I can't seem to figure this one out... I've searched MSDN and Goog, and made my best guesses to no avail,, so help would be much appreciated! public ref class T sealed : public System::Collections::IEnumerable , public System::Collections::Generic::IEnumerable<int> { // How to implement GetEnumerator() for both interfaces? // Compiler complains that functions differ only in return type // which I understand, but can't get the right...
by: Lars | last post by:
Hi, I have a base class holding a generic list that needs to be accessed by both the base class and its subclasses. What is the best solution to this? I am fairly new to generics, but I am aware of that fact that if you have a class B, that inherits from A, then List<Bdoes NOT inherit from List<A>. So I understand why the example below does not compile, but I fail to
by: Tigger | last post by:
I have an object which could be compared to a DataTable/List which I am trying to genericify. I've spent about a day so far in refactoring and in the process gone through some hoops and hit some dead ends. I'm posting this to get some feedback on wether I'm going in the right direction, and at the same time hopefully save others from going through the process.
by: mps | last post by:
I want to define a class that has a generic parameter that is itself a generic class. For example, if I have a generic IQueue<Tinterface, and class A wants to make use of a generic class that implements IQueue<Tfor all types T (so it can make use of queues of various object types internally). As useful as this is, it doesn't seem possible. The natural (but illegal) notation would be something like class A<QueueClasswhere QueueClass :...
by: rkausch | last post by:
Hello everyone, I'm writing because I'm frustrated with the implementation of C#'s generics, and need a workaround. I come from a Java background, and am currently writing a portion of an application that needs implementations in both Java and C#. I have the Java side done, and it works fantastic, and the C# side is nearly there. The problem I'm running into has to do with the differences in implementations of Generics between the two...
by: tadmill | last post by:
Hi, Is it possible for a generic list class to use Reflection on the generic type being used to detect a property within that type that refers to the same generic class, only with a different type as the parameter? From various posts and help, this is what I've got so far: public class DataList<T: BindingList<T>
by: Lloyd Dupont | last post by:
Don't mistake generic type for what you would like them to be!! IFoo<Ahas nothing in common with IFoo<B>! They are completely different type create dynamically at runtime. What you ask is a bit akin to ask: "the System.Web.UI and System.Windows.Controls namespace both contains a Control class, could I use one in place of the other? common they have the same name!" If you want to use a method common to both you should do as Alun...
by: hcaptech | last post by:
This is my Test.can you help me ? 1.Which of the following statement about C# varialble is incorrect ? A.A variable is a computer memory location identified by a unique name B.A variable's name is used to access and read the value stored in it C.A variable is allocated or deallocated in memory during runtime D.A variable can be initialized at the time of its creation or later 2. The.……types feature facilitates the definition of classes...
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.