Casting and Type Conversions

Type conversion is converting one type of data to another type. It is also known as Type Casting. In C#, type casting has two forms:

  • Implicit type conversion – These conversions are performed by C# in a type-safe manner. For example, are conversions from smaller to larger integral types and conversions from derived classes to base classes.(সফটওয়ারের দায়িত্তে)
  • Explicit type conversion – These conversions are done explicitly by users using the pre-defined functions. Explicit conversions require a cast operator.(নিজের দায়িত্তে)

The following example shows an implicit type conversion:

using System;
namespace TypeConversionApplication 
{
   class ImplicitConversion 
   {
      static void Main(string[] args) 
      {
         int i = 100;
         long = i
         
         // implicit conversion -- no cast needed
         Console.WriteLine(i);
         Console.ReadKey();
      }
   }
}

The following example shows an explicit type conversion:

using System;
namespace TypeConversionApplication 
{
   class ExplicitConversion 
   {
      static void Main(string[] args) 
      {
         double d = 5673.74; 
         int i;
         
         // cast double to int. // big to small 
         i = (int)d;
         Console.WriteLine(i);
         Console.ReadKey();
      }
   }
}

 

Author:

Since March 2011, have 8+ years of professional experience on software development, currently working as Senior Software Engineer at s3 Innovate Pte Ltd.

Leave a Reply