Data Type Conversions in C# with real time example



In This Post We Will Learn   Data Type Conversions


1.   Implicit Conversions
2.   Explicit  Conversions
3.   Different between Parse() and TryParse()

Implicit Conversion is done by the compiler 

1.  When there is no loss of  information if the conversion is done 
2.  if there is no possibility of throwing  exception during the conversion 

Example :  Converting an int to a float will not loose any data and no Exception will be thrown,
hence an implicit conversion can be done.



  • using System;


  • namespace Datatypes_conversion
  • {
  •     class Program
  •     {
  •         static void Main(string[] args)
  •         {

  •            // Implicit Convertion Real Time Example 

  •             int r = 100;
  •             float m = r;
  •             Console.WriteLine(m);
  •             Console.ReadLine();


  •         }
  •     }
  • }





  • Explicit  Conversions:


  • using System;


  • namespace Datatypes_conversion
  • {
  •     class Program
  •     {
  •         static void Main(string[] args)
  •         {

  •             float f = 100.24F;

  •             // Cannot Implicity convert float to int 
  •             // Fractional Part will be lost. Float is a bigger data type than int , so there is also a possibility of overflow exception 

  •             // int i =f;
  •             // Use explicit Conversion using cast () operator 
  •             int i = (int)f;

  •             //Or use Convert class
  •             // int i = Convert.ToInt32(f);
  •             Console.WriteLine(i);



  •         }
  •     }
  • }










  • Comments

    Popular posts from this blog

    CREATING INTERNET APPLICATION PROJECT & MVC USING DATA BASE FIRST APPROACH

    Real Time Example add dynamic fields using jquery looking Treeview

    Nullable Type In C# with Example

    How to create DATA BASE And Tables in MSSQL Server

    Basic -C# Reading and writing to a console