Saturday, January 8, 2011

TypeCasting ( Implicit and Explicit )

Type Casting
Casting means to throw or turn a certain direction or state. Type casting is a mechanism to convert data of one type into data of another type (e.g. int to long, int to float, long to double, and so on).
If you have done coding in c# than you should already know that it is common to assign a value of one integer into another type of integer. If the two types are compatible (agreed with each other) than casting is possible. If you want to assign an int value to a long variable it is possible because both data type agreed and this is called implicit type casting. If you want to assign double to byte (incompatible types) than it’s possible to change the casting between incompatible types to achieve this you must use a cast to perform explicit casting. Two types of typecasting are:-

Implicit Typecasting
  • Converting data of small data type into large data type (e.g. int to long, byte to int).
  • To achieve implicit casting both types should compatible and the destination type must be larger than the source type.
  • Implicit casting is performed automatically by c# compiler for you.
  • No loss of data in implicit casting.



Typecasting
Implicit Typecasting
Explicit Typecasting


  • Converting data from large data type into small data type (e.g. int to byte, long to int)
  • This Conversion will not be perform automatically because the destination is smaller than the source.
  • You must use a cast to perform explicit casting.
  • Chance of losing data.


Typecasting
Explicit Typecasting


Typecasting
Result 

If not using cast then?
If not using cast when casting incompatible types then you will be facing some problem shown in picture below.
Typecasting
Errors when not using cast
Both types (e.g. short to byte, int to short, float to int) are not compatible with each other that’s why it requires cast.

4 comments:

  1. does that mean k exchanging values from float to int? is it typecasting?

    ReplyDelete
  2. i thnk typecasting is something k agr i want to add 2 into 3 now if i use operator called * instead of + and still the answer i get is 5 cause i typecast the operator,correct me if i m wrong?

    ReplyDelete
  3. yes.. and that will be explicit typecasting.. as i have explain via example.. I have taken float = 3.142 and exchanging the value and changing the cast of that value that is float to int.. hope you have get your answer.

    ReplyDelete
  4. thats not typecasting thats operator overloading your talking about..

    ReplyDelete