Click here to Skip to main content
11,576,977 members (59,757 online)
Click here to Skip to main content

Tagged as

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

, 30 Dec 2010 CPOL 10.6K 4
Rate this:
Please Sign up or sign in to vote.
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.

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:

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

Consultant cons = new Consultant();
 cons.Age = 25;
 ....
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.

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

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

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)

Share

About the Author

Pranay Rana
Software Developer (Senior) GMind Solusion
India India

Microsoft C# MVP (12-13)


Hey, I am Pranay Rana, working as a ITA in 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:



You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 1 Pin
mbb015-Jan-11 22:12
membermbb015-Jan-11 22:12 
GeneralMy vote of 1 Pin
Peter_Bernheim4-Jan-11 4:11
memberPeter_Bernheim4-Jan-11 4:11 
GeneralMy vote of 2 Pin
_Zorro_3-Jan-11 6:04
member_Zorro_3-Jan-11 6:04 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150603.1 | Last Updated 31 Dec 2010
Article Copyright 2010 by Pranay Rana
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid