Friday, December 31, 2010

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

Shout it kick it on DotNetKicks.com
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.

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.

Exmaple
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.

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

29 comments:

  1. It is easier to tell, than to make.

    ReplyDelete
  2. The author is really cool. But some of the commentators are just posting stupid words.

    ReplyDelete
  3. What is your real name? Maybe I can reply you on your Facebook page.

    ReplyDelete
  4. Thank you so very much for posting this… Absolutely LOVE it!! Wish there was a way to “fav” individual posts on WordPress, would definitely favor this post.

    Regards, Aron
    check my site

    ReplyDelete
  5. Simply awesome. And here I thought my generation was the first to master dry wit. Seems I was wrong. ;)

    R, Aron
    here's my site too

    ReplyDelete
  6. I will add this blog to my favorites, it is great.

    ReplyDelete
  7. I real lucky to find this web site on bing, just what I was looking for : D as well saved to favorites .
    some really interesting points you have written.

    ReplyDelete
  8. Howdy this metter is very interesting. Keep it going man !

    ReplyDelete
  9. Howdy this topic is hugely interesting. Keep it going friend !

    ReplyDelete
  10. Best blog info)
    http://takethepill.biz

    ReplyDelete
  11. Only God knows what I was supposed to do without your help, guys.

    ReplyDelete
  12. This comment has been removed by a blog administrator.

    ReplyDelete
  13. I am thankful that I found this web site, precisely the right information that I was searching for! .

    ReplyDelete
  14. I will really love for you to guests posting on your own blog

    ReplyDelete
  15. Просто хорошая страничка

    ReplyDelete
  16. The authoritative answer
    my favorite post :) http://auto.jkr30.com/auto/ssangyong-goes-electric-mit-mean-looking-kev2-concept/

    ReplyDelete
  17. I must admit , the one who wrote nishtyak nakropal .

    ReplyDelete
  18. thanks, very good =)

    ReplyDelete
  19. Maybe you could write next articles referring to this article. I wish to read even more things about it!

    ReplyDelete
  20. I really appreciate this post. I have been looking all over for this! Thank goodness I found it on Bing.

    ReplyDelete
  21. I think this is among the most significant information for me. And i am glad reading your article.

    ReplyDelete
  22. This is actually the type of information I have been looking for. Thank you for posting this information.

    ReplyDelete

  23. Hi! One of the better to provide a massive thumbs upward to the fantastic information you should have right here with this publish.

    ReplyDelete

  24. You should keep it up forever! Good Luck.

    ReplyDelete
  25. What is your real name? Maybe I can reply you on your Facebook page.

    ReplyDelete
  26. I think this is among the most significant information for me. And i am glad reading your article.

    ReplyDelete
  27. Производственная компания «М-СЕТ» специализируется на производстве сварных сеток в рулонах, имеющих широкое применение в различных строительных работах.
    Производство сварной сетки выполняется на многоточечных сварных машинах, методом контактно-точечной сварки крестообразных соединений. Все пересечения и стыки прутьев тщательно сварены, благодаря чему конструкция отличается превосходным качеством и является одной из самых прочных.
    На нашем сайте Вы можете посмотреть образцы нашей продукции и связаться с нами
    [url=http://setka-vlg.ru/]армирование железобетонных конструкций
    [/url]

    ReplyDelete
  28. Sans une ordonnance [url=http://viagraprixenligne.com#392] viagra generique[/url] Remise [url=http://viagrasildenafilprix.com#586] viagra prix[/url] Remise Viagra Pas de RX [url=http://viagrageneriqueprix.com#20]viagra[/url] Sans une ordonnance Cynergy savoirs traditionnels est rapidement devenu connu comme l'ingrédient de choix pour les augmentant la production de collagène de votre deux, et votre acide hyaluronique [url=http://levitra-generique.eu#602]levitra en ligne[/url] En ligne

    ReplyDelete