C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Size: The program reveals that the long type is represented in 8 bytes—twice as many as an int.
Note: The default value is 0. And finally long is aliased to the System.Int64 struct internally.
C# program that uses long type
using System;
class Program
{
static void Main()
{
long a = 100;
long b = -100;
// Long can be positive or negative.
Console.WriteLine(a);
Console.WriteLine(b);
// Long is very long.
Console.WriteLine(long.MinValue);
Console.WriteLine(long.MaxValue);
// Long is 8 bytes.
Console.WriteLine(sizeof(long));
// Default value is 0.
Console.WriteLine(default(long));
// Long is System.Int64.
Console.WriteLine(typeof(long));
}
}
Output
100
-100
-9223372036854775808
9223372036854775807
8
0
System.Int64
Tip: If there is a chance you have an invalid format, please use the TryParse method instead.
C# program that uses long.Parse
using System;
class Program
{
static void Main()
{
string value = "9223372036854775807";
long n = long.Parse(value);
Console.WriteLine(n);
}
}
Output
9223372036854775807
Alias: The ulong keyword in the C# language is actually an alias to the System.UInt64 type in the base class library.
UInt64: Sometimes it is better to specify the UInt64 type instead as a reminder of the bit size.
Next: The program shows how to declare a ulong and then access some of its static properties.
StaticC# program that uses ulong
using System;
class Program
{
static void Main()
{
//
// Declare ulong variable.
//
ulong value1 = 100;
Console.WriteLine(value1);
// This won't compile:
// value1 = -1;
//
// Look at MaxValue and MinValue.
//
Console.WriteLine(ulong.MaxValue);
Console.WriteLine(ulong.MinValue);
//
// Parse string into ulong type.
//
ulong value2 = ulong.Parse("100");
Console.WriteLine(value2);
//
// Compare two ulong values.
//
Console.WriteLine(value1 == value2);
//
// Write the typeof operator result.
//
Console.WriteLine(typeof(ulong));
}
}
Output
100
18446744073709551615 <-- Max
0 <-- Min
100
True
System.UInt64
Error:
Constant value -1 cannot be converted to a ulong.
Minimum: The minimum value of the ulong type is zero. This is because it has no sign bit, which is why it is called an unsigned value.
Caution: The Parse method will throw System.FormatException when it is passed an invalid parameter.
FormatExceptionValueType: Numeric types inherit from the System.ValueType struct first, and then from the object type.
And: This cost is incurred in method calls and field usages. Many tiny slowdowns will add up.