Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Implicit conversion from Int32 to Decimal in C#
The int type represents a 32-bit signed integer (Int32) in C#. C# allows implicit conversion from int to decimal because this conversion is always safe and does not result in data loss. The decimal type has a much larger range and precision than int.
Syntax
The syntax for implicit conversion from Int32 to decimal is straightforward −
int intValue = 123; decimal decimalValue = intValue; // implicit conversion
No explicit casting is required because the conversion is safe and automatic.
How Implicit Conversion Works
When you assign an int value to a decimal variable, the compiler automatically performs the conversion. This happens because:
The
decimaltype can hold all possibleintvalues without loss of dataNo precision is lost during the conversion
The conversion is considered "widening" (from smaller to larger type)
Example
using System;
public class Demo {
public static void Main() {
int val = 767;
decimal d;
Console.WriteLine("Implicit conversion from Int32 (integer) to Decimal");
d = val;
Console.WriteLine("Original int value: " + val);
Console.WriteLine("Converted decimal value: " + d);
Console.WriteLine("Type of d: " + d.GetType());
}
}
The output of the above code is −
Implicit conversion from Int32 (integer) to Decimal Original int value: 767 Converted decimal value: 767 Type of d: System.Decimal
Multiple Conversions Example
using System;
public class ConversionDemo {
public static void Main() {
int[] intValues = {392, -150, 0, 2147483647};
Console.WriteLine("Int32 to Decimal Conversions:");
Console.WriteLine("Int32 Value\t\tDecimal Value");
Console.WriteLine("===========\t\t=============");
foreach (int value in intValues) {
decimal convertedValue = value; // implicit conversion
Console.WriteLine($"{value}\t\t\t{convertedValue}");
}
}
}
The output of the above code is −
Int32 to Decimal Conversions: Int32 Value Decimal Value =========== ============= 392 392 -150 -150 0 0 2147483647 2147483647
Key Points
No data loss: All int values can be exactly represented as decimal values
Automatic conversion: No casting operator needed
Safe operation: The conversion never throws exceptions
Maintains value: The numeric value remains exactly the same after conversion
Conclusion
Implicit conversion from Int32 to decimal in C# is a safe, automatic operation that preserves the exact numeric value. Since decimal can represent all possible int values without precision loss, the compiler allows this conversion without requiring explicit casting, making it convenient for mathematical operations involving mixed numeric types.
