Explicit and Implicit Casting of Object and Use of 'is','as' keywords in C#

No.of Views638
Bookmarked0 times
Downloads 
Votes0
By  pranay rana   On  11 Jan 2011 19:01:16
Tag : CSharp , Miscellaneous
In this article 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.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

In this article 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

Image Loading

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.

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

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.

C# Code

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 its 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 than you need to convert it explicitly.

Consultant cons = new Consultant();
cons.Age = 25;
// code
object obj = cons;
ProcessData((Employee) obj);

Note
Above code not give any kind of complier error but it throws runtime InvalidCastException if it 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 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;

Example

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

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

Example

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

Difference between as and is

  1. 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.
  2. 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.

Conclusion

'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 article.hopes help and thank you for reading.

 

 
Sign Up to vote for this article
 
About Author
 
pranay rana
Occupation-CEO
Company-GMind Solusion
Member Type-Senior
Location-India
Joined date-08 Jan 2011
Home Page-http://pranayamr.blogspot.com
Blog Page-http://pranayamr.blogspot.com
Hey, I am Pranay Rana, working as a Senior Software engineer in mid-size company located in ahmedabad. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 4.3 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 me on my blog - http://pranayamr.blogspot.com/ StackOverFlow - http://stackoverflow.com/users/314488/pranay My CV :- http://careers.stackoverflow.com/pranayamr
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top