The ulong keyword denotes an integral type that stores values according to the size and range shown in the following table.
Type | Range | Size | NGWS Type |
---|---|---|---|
ulong | 0 to 18,446,744,073,709,551,615 | Unsigned 64-bit integer | System.UInt64 |
You can declare and initialize a ulong variable like this example:
ulong myUlong = 9223372036854775808;
When an integer literal has no suffix, its type is the first of these types in which its value can be represented: int, uint, long, ulong. In this example, it is of the type ulong.
You can also use suffixes to specify the type of the literal according to the following rules:
L
or l
, the type of the literal integer will be either long or ulong according to its size.U
or u
, the type of the literal integer will be either uint or ulong according to its size.UL
, ul
, Ul
, uL
, LU
, lu
, Lu
, or lU
, the type of the literal integer will be ulong.
For example, the output of the following three statements will be the system type UInt64, which corresponds to the alias ulong:
Console.WriteLine(9223372036854775808L.GetType()); Console.WriteLine(123UL.GetType()); Console.WriteLine((123UL + 456).GetType());
A common use of the suffix is with calling overloaded methods. Consider, for example, the following overloaded methods that use ulong and int parameters:
public static void MyMethod(int i) {} public static void MyMethod(ulong l) {}
Using a suffix with the ulong parameter guarantees that the correct type is called, for example:
MyMethod(5); // Calling the method with the int parameter MyMethod(5UL); // Calling the method with the ulong parameter
There is a predefined implicit conversion from ulong to float, double, or decimal.
There is no implicit conversion from ulong to any integral type. For example, the following statement will produce a compilation error without an explicit cast:
long myLong = 8UL; // Error: no implicit conversion from ulong
There is a predefined implicit conversion from byte, ushort, uint, or char to ulong.
Also, there is no implicit conversion from floating-point types to ulong. For example, the following statement generates a compiler error unless an explicit cast is used:
ulong x = 3.0; // Error: no implicit conversion from double ulong y = (ulong)3.0; // OK: explicit conversion
For information on arithmetic expressions with mixed floating-point types and integral types, see float and double.
For more information on implicit numeric conversion rules, see the Implicit Numeric Conversions Table.
C# Keywords | Integral Types Table | Built-in Types Table | Implicit Numeric Conversions Table | Explicit Numeric Conversions Table