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 UInt64 to Decimal in C#
The ulong type represents a 64-bit unsigned integer (UInt64) that can store values from 0 to 18,446,744,073,709,551,615. C# supports implicit conversion from ulong to decimal, meaning the conversion happens automatically without requiring explicit casting.
This conversion is safe because the decimal type can represent all possible ulong values without data loss, though the internal representation changes from integer to floating-point decimal format.
Syntax
Following is the syntax for implicit conversion from ulong to decimal −
ulong ulongValue = value; decimal decimalValue = ulongValue; // implicit conversion
How It Works
The conversion occurs automatically because:
The
decimaltype has sufficient precision to represent allulongvaluesNo data loss occurs during the conversion
The compiler recognizes this as a safe widening conversion
Example
using System;
public class Demo {
public static void Main() {
ulong val = ulong.MaxValue;
decimal dec;
Console.WriteLine("Implicit conversion from UInt64 to Decimal");
Console.WriteLine("Original ulong value: " + val);
dec = val; // implicit conversion
Console.WriteLine("Converted decimal value: " + dec);
// Verify the values are equal
Console.WriteLine("Values are equal: " + (dec == val));
}
}
The output of the above code is −
Implicit conversion from UInt64 to Decimal Original ulong value: 18446744073709551615 Converted decimal value: 18446744073709551615 Values are equal: True
Using Different UInt64 Values
Example
using System;
public class ConversionDemo {
public static void Main() {
// Different ulong values
ulong[] values = { 0, 1000, ulong.MaxValue / 2, ulong.MaxValue };
Console.WriteLine("UInt64 to Decimal Conversion Examples:");
Console.WriteLine("=====================================");
foreach (ulong val in values) {
decimal dec = val; // implicit conversion
Console.WriteLine($"ulong: {val,20} -> decimal: {dec,20}");
}
}
}
The output of the above code is −
UInt64 to Decimal Conversion Examples: ===================================== ulong: 0 -> decimal: 0 ulong: 1000 -> decimal: 1000 ulong: 9223372036854775807 -> decimal: 9223372036854775807 ulong: 18446744073709551615 -> decimal: 18446744073709551615
Conclusion
Implicit conversion from ulong to decimal in C# is automatic and safe, preserving all data without loss. This conversion is useful when working with large unsigned integers that need to be processed using decimal arithmetic operations or when interfacing with APIs that expect decimal values.
