Introduction
Look at the example given below.
Here the runtime is more suspicious; if the type of object in memory does not match the cast, the runtime will throw an InvalidCastException. We should be prepared to catch this exception and handle it appropriately if it occurs. However, catching an exception and attempting to recover in the event that the type of an object is not what we expected it to be is a rather cumbersome approach. C# provides two more very useful operators that can help us to perform casting in a much more elegant manner by using the "is" and "as" operators. Let's have some discussion of the operators.
Is Operator
The "is" operator is used to check whether the run-time type of an object is compatible with a given type or not. In other words, we use the "is" operator to verify that the type of an object is what we expect it to be. Let's look at its syntax.
Expression is type
Example of the "is" operator.
In the above example, I'll be checking whether object o is a class or not. If the argument passed is not a class then the application will jump to the message 'o is neither class1 nor class2'.
As Operator
The "as" operator is used to perform conversions between compatible types. Actually, the "as" operator fulfills a similar role like "is" but in a slightly truncated manner. Let's look at its syntax.
Expression as type
Example of the "as" operator.
In the above example, each and every value is cast to a string using the "as" operator and assigned to a string variable which is shown on the console.
So, that's all about the "as" and "as" operators. Thanks for joining this article.
HAVE A HAPPY CODING!!