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
class MyIComparableT : IComparable<MyIComparableT>
1. With an instance
The "is" operator just do perfectly the job, so no problem here
MyIComparable t = new MyIComparable();
Console.WriteLine(t is IComparable);
Console.WriteLine(t is IComparable<MyIComparable>);
MyIComparableT t2 = new MyIComparableT();
Console.WriteLine(t2 is IComparable);
Console.WriteLine(t2 is IComparable<MyIComparableT>);
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.
Type myIComparable = typeof(MyIComparable);
Type myIComparableT = typeof(MyIComparableT);
Type iComparableT = typeof(IComparable<>)
Type iComparable = typeof(IComparable);
Now let's compare easily !
And when I remember I was dealing with the GetInterface or GetInterfaces method. Much simpler like that ! Pretty cool no ?