C# Type Conversion with Examples

In this tutorial, we will learn about the type conversion, types of type conversion with the help of examples in C#. By IncludeHelp Last updated : April 07, 2023

C# Type Conversion

Type conversion is a basic and important feature of almost all programming languages. Type conversion is used to convert one type of data into another type. It is also known as typecasting.

C# Type Conversion / Typecasting Types

There are two type of type casting/conversions:

  1. Implicit or Automatic Type Conversion
  2. Explicit Type Conversion

1) Implicit or Automatic Type Conversion

Implicit type casting is performed in type safe manner in c#. When we convert data from smaller to larger integral type and conversion from child class to parent class in known as implicit type conversion.

C# Example of Implicit or Automatic Type Conversion

using System;

namespace ImplicitTypeConversion {
  class Program {
    static void Main(string[] args) {
      int intNumber = 108;

      // Getting the type
      Type type1 = intNumber.GetType();

      // Implicit Conversion from int to double
      double doubleNumber = intNumber;

      // Getting the type
      Type type2 = doubleNumber.GetType();

      // Value & type before implicit conversion
      Console.WriteLine("intNumber value: " + intNumber);
      Console.WriteLine("intNumber Type: " + type1);

      // Value & type after implicit conversion
      Console.WriteLine("doubleNumber value: " + doubleNumber);
      Console.WriteLine("doubleNumber Type: " + type2);

      Console.ReadLine();
    }
  }
}

Output

intNumber value: 108
intNumber Type: System.Int32
doubleNumber value: 108
doubleNumber Type: System.Double

2) Explicit Type Conversion

This conversion is not performed automatically. For explicit type conversions we need to use pre-define functions. Sometime we need to use some conversion operators.

C# Example of Explicit Type Conversion

using System;

namespace ExplicitTypeConversion {
  class Sample {
    static void Main(string[] args) {
      double var1 = 3.245;
      int var2 = 0;

      // Implicit Conversion from double to int
      var2 = (int) var1;

      // Value & type before implicit conversion
      Console.WriteLine("var1 value: " + var1);
      Console.WriteLine("var1 Type: " + var1.GetType());

      // Value & type after implicit conversion
      Console.WriteLine("var2 value: " + var2);
      Console.WriteLine("var2 Type: " + var2.GetType());
      
      Console.ReadLine();
    }
  }
}

Output

var1 value: 3.245
var1 Type: System.Double
var2 value: 3
var2 Type: System.Int32




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.