févr. 20

Hello all,

we are quite in a rush at job right now that prevent me from blogging. Anyway, I always keep an eye on things I can learn and tonight while I was browsing in the Lutz Roeder's Reflector, I have seen something very interesting.
A few days ago, with Damien Pinauldt, I was wondering how to to detect if a type implements a given interface or not. Of course if we have an instance, this is very simple but when having only a type, I was not knowing how to do that. Here is what I have found and some recall.

1. Let's create some classes for the demo

class MyIComparable : IComparable
   //Implementation omitted
class MyIComparableT : IComparable<MyIComparableT>
   //Implementation omitted

1. With an instance

The "is" operator just do perfectly the job, so no problem here

//1. Let's test our type implementing IComparable
MyIComparable t = new MyIComparable();
Console.WriteLine(t is IComparable);                  //True
Console.WriteLine(t is IComparable<MyIComparable>);   //False
//2. And now our type implementing IComparable<T>
MyIComparableT t2 = new MyIComparableT();
Console.WriteLine(t2 is IComparable);                 //False
Console.WriteLine(t2 is IComparable<MyIComparableT>); //True

2. With a Type

First "difficulty" : we need to create a "Type" object holding each interface we want to test. Here the typeof operator and the MakeGenericType will help us.

//Let's create Types variable
//MakeGenericType will help us creating the type 
//by defining what the "T" is
Type myIComparable = typeof(MyIComparable);
Type myIComparableT = typeof(MyIComparableT);
Type iComparableT = typeof(IComparable<>)
Type iComparable = typeof(IComparable);

Now let's compare easily !

//1. Let's test our type implementing IComparable
Console.WriteLine(iComparable.IsAssignableFrom(myIComparable));  //True
Console.WriteLine(iComparableT.IsAssignableFrom(myIComparable)); //False
//2. And now our type implementing IComparable<T>
Console.WriteLine(iComparable.IsAssignableFrom(myIComparableT));  //False
Console.WriteLine(iComparableT.IsAssignableFrom(myIComparableT)); //True

And when I remember I was dealing with the GetInterface or GetInterfaces method. Much simpler like that ! Pretty cool no ?

Tags: | | | |


Ajouter un commentaire

  • Commentaire
  • Aperçu immédiat