Saturday, June 2, 2012

If Type Implements Interface == true - Part II

This post is the continuation of the last post where we discussed how to check whether a type implements some interface. you can find this discussion here [http://www.shujaat.net/2012/06/if-type-implements-interface-true.html].

In this post we will continue this discussion by introducing Type.GetInterfaceMap(). System.Type provides this type to provide the mapping between interface and type's method. We can determine what type's method implement which interface one. This mapping can be used by framework developers to do amazing things.

Let's start by discussing how we can use this to determine whether a type implements the specified interface. We introduce this method which accepts the type and interfaceType as parameters. The method returns true if the type actually implements the interface and false otherwise.


Let's use this method as follows:


Here we are checking whether the type Student implements IStudent and ICalculator<int> interface. Definitely the first statement is true and the other one is false. Let's run this and see if the result is as expected.


Basically Type.GetInterfaceMap doesn't return boolean, it returns System.Reflection.InterfaceMapping structure type if the type actually implements the interface. In case the type doesn't implement that, it just throws an ArgumentException. We are catching the exception in our code and returning false in this case.


As discussed above, the main purpose of availability of this method in System.Type is to determine the interface methods and their corresponding methods in target type. Let's print this mapping for the provided type and an interface.


Let's use this for Calculator<int> and ICalculator<int>.


This would result in the following output:


Type Casting
In this method, we do an explicit cast into the interface type. Obviously, the type of interface must be known at compile time. If the object's type doesn't implement the specified interface or it does not inherit from the type specified type then it would result in Invalid Cast Exception. Obviously, this method wouldn't be recommended for a production code. Please see this msdn article for type casting and conversion [http://msdn.microsoft.com/en-us/library/ms173105.aspx].


Zindabad!!!

No comments: