Home
C#
short, ushort Types
This page was last reviewed on Oct 6, 2024.
Dot Net Perls
Short and ushort. The C# short type reduces the memory usage of integers. This compact type represents a number in 2 bytes—16 bits—half the size of an int.
Short is aliased to System.Int16, and this is part of the C# specification. Ushort, meanwhile, is aliased to System.UInt16. Unsigned numbers cannot be negative.
int
Short example. We use the short type as a storage location for positive or negative integers. The short type is aliased to the System.Int16 struct.
struct
Part 1 We use a short local variable. We can add values to a short. This computation is expressed in the same way as adding numbers to integers.
Part 2 Because ushort is 16 bits, it will use about half the memory in an array as an int. With large arrays, this can improve performance.
using System; // Part 1: demonstrates a short value type used as local variable. short number = 11; Console.WriteLine(11); number = -1; // Can be negative Console.WriteLine(number); Console.WriteLine(number == -1); // Can use == operator Console.WriteLine(number + 100); // Can use + operator Console.WriteLine(number.GetType()); Console.WriteLine(typeof(short)); Console.WriteLine(short.MinValue); Console.WriteLine(short.MaxValue); // Part 2: find the memory usage for a short value in a large array. long bytes1 = GC.GetTotalMemory(false); short[] array = new short[1000 * 1000]; array[0] = 1; long bytes2 = GC.GetTotalMemory(false); // Console.WriteLine(bytes1); // Console.WriteLine(bytes2); Console.WriteLine(((bytes2 - bytes1) / (1000 * 1000)).ToString() + " bytes per short");
11 -1 True 99 System.Int16 System.Int16 -32768 32767 2 bytes per short
Short range. Consider the values returned by short.MinValue and short.MaxValue. The smallest number a short can hold is -32768. And the largest is 32767.
short.MinValue = -32768 short.MaxValue = 32767
ushort.MinValue = 0 ushort.MaxValue = 65535
Parse shorts. This program uses 2 string literals as the input data: "100" and "100000." The value 100 can be stored in a short. The value 100000 cannot be.
int.Parse
Info The call to short.Parse succeeds without causing an error because 100 is a valid short.
So With the 2 calls to short.TryParse, the first call succeeds and you can use the result, but the second call returns false.
true, false
using System; const string value1 = "100"; const string value2 = "100000"; // Can use short.Parse. short sh1 = short.Parse(value1); Console.WriteLine("sh1 = {0}", sh1); // Can use short.TryParse. short sh2; if (short.TryParse(value1, out sh2)) { Console.WriteLine("sh2 = {0}", sh2); } // Returns false: short.TryParse on number too large. short sh3; if (short.TryParse(value2, out sh3)) { Console.WriteLine("sh3 = {0}", sh3); // Never reached. }
sh1 = 100 sh2 = 100
Ushort example. The ushort type is a value type. This means the actual value of the variable is stored in its storage location memory.
Part 1 Local ushort variables are stored on the method stack. The ushort type occupies 16 bits—it is half the size of an int value.
Part 2 The typeof operator uses an optimized reflection method to get the type pointer for an object type.
typeof
Part 3 The type of a ushort variable is actually a System.UInt16 type, because ushort is aliased to that type in the System namespace.
Part 4 We use an array of unsigned shorts. The elements in the array are always initialized to have all their bits set to zero.
int Array
using System; // Part 1: declare and initialize ushort value. ushort value1 = 1000; // This won't compile: // value1 = -1; // Write value. Console.WriteLine(value1); // Part 2: write type of ushort. Console.WriteLine(typeof(ushort)); // Part 3: alternative syntax for declaring a ushort value. UInt16 value2 = 1000; // Write value. Console.WriteLine(value2); // Part 4: declare a ushort array. ushort[] array1 = new ushort[2]; array1[0] = 5; // Write array elements. Console.WriteLine(array1[0]); Console.WriteLine(array1[1]); // <-- Default is zero. // Write minimum and maximum values. Console.WriteLine("MIN: {0}", ushort.MinValue); Console.WriteLine("MAX: {0}", ushort.MaxValue);
1000 System.UInt16 1000 5 0 MIN: 0 MAX: 65535
Ushort error. At compilation time, the C# compiler uses a checked context to check for overflow of numeric variables. It tries to detect an invalid program.
checked
And The compiler detects the assignment of a negative constant to the ushort variable, and gives you a helpful error.
Note This will help you avoid hard-to-find bugs later in the program's development.
class Program { static void Main() { ushort test = -1; } }
Error CS0031 Constant value '-1' cannot be converted to a 'ushort'
Ushort performance. If a ushort is smaller than an int, is it also faster to use? This program tests the performance of incrementing and looping with a ushort.
Version 1 The method loops over a ushort and increments one. The loop branches on a ushort (in a loop boundary test).
Version 2 This code uses int instead of ushort. It performs the same actions as the ushort method but with int.
Result It is faster to use an int in loops and increment statements. Ushort does not help runtime speed in this test.
using System; using System.Diagnostics; using System.Runtime.CompilerServices; class Program { const int _max = 1000000; static void Main() { // Version 1: use ushort method. var s1 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { Test1(); } s1.Stop(); // Version 2: use int method. var s2 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { Test2(); } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } static void Test1() { ushort result = 0; for (ushort i = 0; i < 100; i++) { result++; } } static void Test2() { int result = 0; for (int i = 0; i < 100; i++) { result++; } } }
62.54 ns ushort method 35.68 ns int method
Summary. In C# programs, short and ushort are sometimes useful. Shorts can be used like native integers as local variables. In large arrays they will save memory usage over other types.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 6, 2024 (rewrite).
Home
Changes
© 2007-2024 Sam Allen.