Pages

Friday, December 31, 2010

Explicit and Implicit Casting of object and Role of 'is' and 'as' keyword in Explicit casting

In this post I am going to discuss about the casting of object form one type to another type and what the thing require to keep in mind when casting object.

Casting basically take place we are using relating between classes i.e INHERITANCE. Classes have parent child relationship i.e is-a relationship between them.
To understand it take example of below diagram

As show in above image Employee and Manager is having is-a relationship with person i.e Inherited from person class.
Now I have one method in my main class which take Employee as argument and do processing on the property of the class.

Implicit conversion
Implicit conversion take place when there is is-a relation between two classes i.e Inherited form other. As per diagram Employee is Inherited from Person Class and so that as per OOD rule there is no need to convert Employee class to Person class.

Solution 2
Make use of 'as' keyword of C#. It does conversion from one object to another object and return Null if it not able to convert. Use it when you want to convert object form one type to another object.Syntax type t =expression as type;

Solution 3
Make use of 'is' keyword of C#. It does conversion from one object to another object and return false if it not able to convert. Use it when you want to check it convertible or not.Syntax type t = expression is type

as operator do conversion form one type to another type and return Null if converstion
fails. There is no need to conversion again if its convertible as shown in example code.

is operator checks weather one object is convertible in another type or not and return false if not. So need to convert object to base type if it convertible as shown in exapmple code.

Summary
'is' and 'as' keyword play important role when we do the casting of the related objects Explicitly. But you need to use it according to situation as we discuss in Difference section of this post.CodeProject