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 16-bit unsigned integer (ushort) to Decimal in C#
ushort represents a 16-bit unsigned integer in C# with a range from 0 to 65,535. C# allows implicit conversion from ushort to decimal because this conversion is always safe and does not result in data loss.
The decimal type can accommodate the entire range of ushort values without precision loss, making implicit conversion possible.
Syntax
Following is the syntax for implicit conversion from ushort to decimal −
ushort ushortValue = value; decimal decimalValue = ushortValue; // implicit conversion
How It Works
The conversion happens automatically without requiring explicit casting or conversion methods. The compiler handles the conversion internally, ensuring the ushort value is properly represented as a decimal.
Example
Here is an example demonstrating implicit conversion from ushort to decimal −
using System;
public class Demo {
public static void Main() {
ushort val = 2567;
decimal dec;
Console.WriteLine("Implicit conversion from 16-bit unsigned integer to Decimal");
dec = val;
Console.WriteLine("UShort value: " + val);
Console.WriteLine("Decimal value: " + dec);
Console.WriteLine("Type of dec: " + dec.GetType());
}
}
The output of the above code is −
Implicit conversion from 16-bit unsigned integer to Decimal UShort value: 2567 Decimal value: 2567 Type of dec: System.Decimal
Using Maximum UShort Value
The following example shows conversion with the maximum ushort value −
using System;
public class Demo {
public static void Main() {
ushort maxUShort = ushort.MaxValue;
decimal dec = maxUShort;
Console.WriteLine("Maximum UShort value: " + maxUShort);
Console.WriteLine("Converted to Decimal: " + dec);
Console.WriteLine("Are they equal? " + (maxUShort == dec));
}
}
The output of the above code is −
Maximum UShort value: 65535 Converted to Decimal: 65535 Are they equal? True
Key Rules
-
The conversion is implicit ? no casting operator is required.
-
No data loss occurs during the conversion.
-
The conversion is widening ? moving from a smaller to larger data type.
-
All
ushortvalues (0 to 65,535) can be exactly represented asdecimal.
Conclusion
Implicit conversion from ushort to decimal in C# is safe and automatic. The compiler handles this conversion without explicit casting because decimal can represent all ushort values without precision loss, making it a widening conversion.
