Click here to Skip to main content
15,895,011 members
Articles / Programming Languages / C#

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

Rate me:
Please Sign up or sign in to vote.
3.78/5 (6 votes)
30 Dec 2010CPOL2 min read 17.7K   5   3
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 things required to be kept in mind when casting object.

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

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

C#
public void ProcessData(Person p)
{
....process data 
Console.WriteLine(p.ToString());
}

Implicit Conversion

Implicit conversion takes place when there is an is-a relation between two classes, i.e., inherited from other. As per the 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.

Example:

C#
public void testdata()
{
 Employee emp = new Employee();
 emp.Age = 25;
 emp.BirthDate = DateTime.Now;
 emp.Height = "5 ' 3";
 emp.salary = 2000;
 emp.type = 1;
 ProcessData(emp);
}

When you compile and run the code, there is no error because it is Implicit conversion from child to parent.

Explicit Conversion

Where there is no relation between classes and if you want to pass the object of another type to method, then you need to convert it explicitly.

Example

C#
Consultant cons = new Consultant();
 cons.Age = 25;
 ....
C#
object obj = cons;
 ProcessData((Employee) obj);

Note

The above code does not give any kind of compiler error, but it throws runtime InvalidCastException if it is not able to cast to the type.

Following is solution to avoid InvalidCastException at runtime because of Explicit conversion.

Solution 1

Catch the exception and handle it.

C#
Consultant cons = new Consultant();
 cons.Age = 25;
 ....
 try
 {
   ProcessData((Employee) cons);
 }
 catch(InvalidCastException ex)
 {
    ... process exception
 }

Solution 2

Make use of 'as' keyword of C#. It does conversion from one object to another object and returns Null if it is not able to convert. Use it when you want to convert object from one type to another object.

Syntax

type t =expression as type;

Example

C#
Employee emp = new Employee();
  Person p = emp as Person; 
  if(p!=null)
  {
   .. process data
  } 
  else
  {
   .. display error message or do another code
  }

Solution 3

Make use of 'is' keyword of C#. It does conversion from one object to another object and returns false if it is not able to convert. Use it when you want to check whether it is convertible or not.

Syntax

type t = expression is type

Example

C#
Employee emp = new Employee();
  if(emp is Person)
  {
    Person p = (Person)emp;
    .. process data
  } 
  else
  {
   .. display error message or do another code
  }

Difference between as and is

  • as operator does conversion form one type to another type and returns Null if conversion fails. There is no need for conversion again if it's convertible as shown in the example code.
  • is operator checks whether one object is convertible to another type or not and returns false if not. So you need to convert object to base type if it is convertible as shown in the example code.

Summary

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India

Microsoft C# MVP (12-13)



Hey, I am Pranay Rana, working as a Team Leadin MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.

For me def. of programming is : Programming is something that you do once and that get used by multiple for many years

You can visit my blog


StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr

Awards:



Comments and Discussions

 
GeneralMy vote of 1 Pin
mbb015-Jan-11 22:12
mbb015-Jan-11 22:12 
GeneralMy vote of 1 Pin
___AV___4-Jan-11 4:11
___AV___4-Jan-11 4:11 
GeneralMy vote of 2 Pin
_Zorro_3-Jan-11 6:04
professional_Zorro_3-Jan-11 6:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.