TheDeveloperBlog.com


C# Long

Long. The long type contains 64 bits, or 8 bytes. It can represent very large integral numbers but not floating-point numbers. It has a sign bit, so it supports positive and negative numbers.

System.Int64 information

long.MinValue = -9223372036854775808
long.MaxValue =  9223372036854775807


Example. First, we show that long variables can be positive or negative. We see the minimum value that can be stored in long, and the maximum value as well. The program reveals that the long type is represented in 8 bytes—twice as many as an int.

Int

Note: As with all numeric types, 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


Parse. As with other numeric types, the long type provides Parse and TryParse methods. Parse will throw exceptions if the input string is invalid. 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


Ulong. If the long type does not provide enough digits in the positive range, you can try the ulong type. You cannot have negative values with ulong. The largest positive integer that can be stored in the ulong type is 20 digits long.

Ulong

Summary. We investigated the long type. This type is twice as large as an int. It has a narrow range of utility. It helps in programs where floating-point numbers are not required and regular integers are too small.

Note: If you need more positive values and no negative values, please consider the ulong type.