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 Int16 to Decimal in C#
The short type in C# represents a 16-bit signed integer (Int16) that can store values from -32,768 to 32,767. C# allows implicit conversion from short to decimal because this conversion is always safe and will never result in data loss.
An implicit conversion means the compiler automatically performs the type conversion without requiring an explicit cast operator. This is possible because decimal has a much larger range and precision than short.
Syntax
The syntax for implicit conversion from Int16 to Decimal is straightforward −
short shortValue = value; decimal decimalValue = shortValue; // Implicit conversion
How Implicit Conversion Works
When you assign a short value to a decimal variable, the compiler automatically converts the 16-bit integer to a 128-bit decimal representation. The original value remains unchanged, but it's stored with decimal precision.
Examples
Basic Implicit Conversion
using System;
public class Demo {
public static void Main() {
short val = -32768;
decimal dec;
Console.WriteLine("Implicit conversion from Int16 to Decimal");
dec = val; // Implicit conversion occurs here
Console.WriteLine("Short value: " + val);
Console.WriteLine("Decimal value: " + dec);
Console.WriteLine("Type of dec: " + dec.GetType());
}
}
The output of the above code is −
Implicit conversion from Int16 to Decimal Short value: -32768 Decimal value: -32768 Type of dec: System.Decimal
Multiple Conversions with Different Values
using System;
public class ConversionDemo {
public static void Main() {
short[] shortValues = { 0, 1000, -1000, 32767, -32768 };
Console.WriteLine("Int16 to Decimal Conversion Examples:");
Console.WriteLine("=====================================");
foreach (short s in shortValues) {
decimal d = s; // Implicit conversion
Console.WriteLine($"short: {s,6} -> decimal: {d}");
}
}
}
The output of the above code is −
Int16 to Decimal Conversion Examples: ===================================== short: 0 -> decimal: 0 short: 1000 -> decimal: 1000 short: -1000 -> decimal: -1000 short: 32767 -> decimal: 32767 short: -32768 -> decimal: -32768
Key Characteristics
| Aspect | Details |
|---|---|
| Conversion Type | Implicit (automatic) |
| Data Loss | None - conversion is always safe |
| Performance | Fast - handled by the compiler |
| Precision | Enhanced - decimal provides higher precision |
Conclusion
Implicit conversion from Int16 to Decimal in C# is a safe, automatic process that preserves the original value while providing enhanced precision. The compiler handles this conversion seamlessly, making it convenient to work with mixed numeric types in calculations and data processing.
