How to use IS and AS keywords in C#

Using as keyword

Dynamic polymorphism which is evaluated at run time not at compile time so we are sure that errors are not known before execution. Like e.g Explicit casting is evaluated at run time.

object test = new Manager();
//You cant cast test to a Department!
Department dept= (Department) test;

So how can we safely use such casting and handle exception

try
{ 
Department dept = (Department) test;
}
catch(InvalidCastException ex)
{ 
...
}

Above code is about handling exception but how about doing some more logical coding in the failed case, coding into catch not good example.

We can determine whether the given type is compatible with another using ‘as’. Compatibility check will return null value.

Using is Keyword
Unlike as keyword is keyword returns false if compatibility between objects or casting failed.

void(Employee emp)
{
if(emp is Department)
     Console.WriteLine("Sorry, emp is not Department..");
}

Here we are checking runtime what incoming base class reference is actually pointing in memory. So we are not using try catch as well here to wrap the casting.

Happy programming..

Number of View :967
  1. No comments yet.

SetPageWidth
Content Protected Using Blog Protector By: PcDrome.

Mahol Dot Org is Stephen Fry proof thanks to caching by WP Super Cache