This article describes how to do safe type casting using the “IS” and “AS” operators in C# programming.
IntroductionType casting is one of the important things in software development. In many situations we need to convert one data type to another data type. Sometimes we get an exception like "Cannot implicitly convert type 'XXXX' to 'YYYY'". To avoid this exception, C# provides the two operators "IS" and "AS" to check object compatibility.IS OperatorThe IS operator is useful for checking compatibility with a given type and it returns true if the object is the same type else false.ExampleThe following code is useful when an object is a type of my custom class type.
AS operatorThe “AS” operator can be used to perform type conversion between compatible reference types or nullable types. In other words, the AS operator checks whether the type of a given object is compatible with the new object type and it returns a non-null value if the type is compatible with the new one, else null.Example
The “AS” operator uses code to convert that is equivalent to the following expression:
Employee employee
Programming C# 5.0