As keyword in C# with Example

As keyword in C# with Example
Rating: 5 - 1 Votes

As keyword in C# with Example

As keyword in C# with Example

As keyword in C# with Example

We have seen how to use is operator before type casting.  Another way to check whether type casting was successful or not, is as keyword.  If the type casting was successful, reference variable point to that object in memory.  If the type casting was failed, then reference variable contains a null value.  So before execution of further code, you can check for reference variable value and can easily avoid any kind of runtime errors.

Easy way to remember when to use is operator and as keyword:

  • Is Operator:  First check and then type cast.
  • As keyword:  First type cast and then check.

 Output:

This is an Employee Class.
Press any key to continue . . .