C# Type Conversion

Updated on     Kisan Patel

Converting one type of variable to another is called casting.

C# supports two kinds of type conversions.

1. Implicit conversions in C#

  1. Implicit conversions are conversions in which one type can directly and safely are converted to another type.
  2. For example, an integer type variable is converted to float type in C#.
  3. In this conversion, there is no loss of data.
using System;

namespace ConsoleApp
{
    class CastingDemo
    {
        static void Main(string[] args)
        {
            int num1 = 123;
            long num2 = num1;
            Console.WriteLine(num1.ToString());
            Console.WriteLine(num2.ToString());
        }
    }
}

Output of the above c# program…

c-sharp-implicit-demo

2. Explicit Conversion in C#

  1. Requires a keyword that converts a data type into another.
  2. For example, to convert a Double into an integer, you have to use int keyword as shown in below example.
using System;

namespace ConsoleApp
{
    class CastingDemo
    {
        static void Main(string[] args)
        {
            double num1 = 5.4458;
            int num2 = (int)num1;
            Console.WriteLine(num1.ToString());
            Console.WriteLine(num2.ToString());
        }
    }
}

Output of the above c# program…

c-sharp-explicit-demo


C#

Leave a Reply