Article

Type Casting in C#


Type Casting in C#

When the variable of one data type is changed to another data type is known as the Type Casting. According to our needs, we can change the type of data.after the declaration of the variable, we cannot declare it again. The value of the variable cannot be assigned to another type of variable unless we implicitly change the type of the variable.

In C#, there are two types of casting

  • Implicit Casting
  • Explicit Casting

Implicit Casting :- 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.

Example:- char -> int -> long -> float -> double


using System;

namespace MyApplication
{
  class Program
  {
    static void Main(string[] args)
    {
      int myInt = 4;
      double myDouble = myInt;  // Automatic casting: int to double

      Console.WriteLine(myInt);
      Console.WriteLine(myDouble);
    }
  }
}

OUTPUT

4
4

Explicit Casting :- These conversions are done explicitly by users using the pre-defined functions. Explicit conversions require a cast operator. There may be compilation error when types not compatible with each other. For example, assigning double value to int data type:


using System;

namespace MyApplication
{
  class Program
  {
    static void Main(string[] args)
    {
      double myDouble = 9.78;
      int myInt = myDouble;  

      Console.WriteLine(myDouble);
      Console.WriteLine(myInt);
    }
  }
}

OUPUT

error CS0266: Cannot implicitly convert type `double' to `int'. An explicit conversion exists (are you missing a cast?)
Compilation failed: 1 error(s), 0 warnings

Now, using Explicit casting must be done manually by placing the type in parentheses in front of the value:

Example:- double -> float -> long -> int -> char


using System;

namespace MyApplication
{
  class Program
  {
    static void Main(string[] args)
    {
      double myDouble = 5.78;
      int myInt = (int) myDouble;  // Manual casting: double to int

      Console.WriteLine(myDouble);
      Console.WriteLine(myInt);
    }
  }
}

OUPUT

5.78
5