When working with type conversions, there are always ways to ensure that an incorrect type conversion does not happen. However, a try/catch is not always the best solution, especially for type conversions. That is why, in c sharp we have the 'is' and 'as' operators.
As the wording indicates, the 'is' operator checks if a particular object type is compatible with another object type. The 'as' operator gets the converted object type, if the conversion is possible at all.
The use case for 'is' is straight forward. You have two objects, and you want to find out if the conversion is possible. If conversion is possible, you would like to convert it, and then do stuff based on that.
The use case for 'as' is when you feel that conversion is pretty much a guaranted and want to get a converted object right away. You could say that 'is' is good enough (since you will do a conversion later anyway) but 'as' makes you cooler because you just saved so many lines of code.
As always, a sample is available at our code repository.
The is and as operator has strong connections to the Liskov substitution principle (which you can read more about in one of our earlier blog posts). The principle states that the base type objects can be used where the derived classes are used.
That is essentially what the is and as operators are doing. Ideally, if you were to follow the standard design guidelines of object oriented programming, you would never have to use the 'is' and 'as' operators. Of course, the key word here is 'ideally'. Further, thanks to Generics, you can simply use a Generic type now and take care of things were you may be using different types.
Follow me on twitter, facebook and instagram for more updates. Thanks!