What is implicit and explicit casting in C#?

The conversion of one data type into another is known as type casting. There are two kinds of type casting in C#:

  1. Implicit casting
  2. Explicit casting

Implicit casting

The conversion of a smaller data type to a larger data type is known as implicit casting. It is done automatically. For example, if the short and int types are being added, the short data type will be converted to the int data type.

Explicit casting

The conversion of a larger data type to a smaller data type is known as explicit casting. To convert the decimal data type to the int data type, (int) is written before the decimal variable.

Note: Converting the larger data value to the smaller data type may cause some data loss.

Example

decimal firstNumber = 50.1234m;
int secondNumber= 2;
Console.WriteLine("Implicit casting:");
Console.WriteLine(firstNumber + secondNumber); // Output: 52.1234
Console.WriteLine((firstNumber + secondNumber).GetType()); // Output: System.Decimal
Console.WriteLine("Explicit casting:");
// Explicitly cast firstNumber to int. Data was lost (.1234)
Console.WriteLine((int)firstNumber + secondNumber); // Output: 52
Console.WriteLine(((int)firstNumber + secondNumber).GetType()); // Output: System.Int32

Explanation

  • Lines 12: We declare two variables of the decimal and int type.
  • Line 5: We print the result of the implicit casting by adding both variables.
  • Line 6: We print the type of the addition with the .GetType() method.
  • Line 10: We print the result of explicit casting by adding after the conversion of the decimal value to the int type.
  • Line 11: We print the type of the addition with the .GetType() method.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved