Day 20 : Casting and Conversion in C#

 

Casting :

          Casting means copying or converting a value from one data type to another data type. Casting is divided into two types :

1) Implicit casting : 

  • Implicit casting is done automatically by compiler when we pass smaller size type value to a larger size type.
  • If we assign larger data type to smaller data type then it will won't work here.
  • Smaller to larger data type : byte > short > int  > long > float > double.
  • Also before converting compiler checks the compatibility i.e only numeric data types are compatible with each other but no conversion is their between numeric to char or boolean.
  • Also char and boolean are not compatible with each other.
  • Their are many compilation error(missing cast) when types are not compatible with each other.
  • Example :




2) Explicit casting : 

  • If we want to assign a value of larger data type  to smaller data type we perform explicit casting.
  • The explicit casting is done manually by user according to their need by placing data type in parenthesis in front of value.
  • This is used for incompatible data types where automatic casting cannot be done.
  • Example :

Conversion :

  • The conversion means converting one type to another.
  • Conversion is same as casting but here we use Convert.To() function for conversion.
  • Some conversion methods are :
  1. ToBoolean() : Converts a type to a boolean value.
  2. ToInt32() : Converts a type to a 32-bit integer.
  3. ToSingle() : Converts a type to a small floating point number.
  4. ToString() : Converts a type to a string.
  5. ToDateTime() : Converts a type(int or string) to date-time structure.                                                  
  • Example : 
                                 

 
Thank You!!!

For more understanding watch below video :

Comments

Popular posts from this blog

Day 3 : JavaScript

SQL Concepts-1

ASP .NET Session Management