What is short and ushort
Both Short (short) and UShort (ushort) are both number variables and hold 16 bits(2 bytes) of data. The ushort is unsigned and cannot hold negative numbers, while short is signed and can hold negative and positive numbers.
Data Type | Range | Struct |
short | -32,768 to 32,767 | System.Int16 |
ushort | 0 to 0 to 65,535 | System.UInt16 |
short and ushort are basically types of int’s (Integers), and they are aliases for System.Int16 and System.UInt16.
By default the data type byte cannot be null. You can force this to be null, if you wish.
Usage of the variable type
It is recommended to declare the variable using ‘short’ or ‘ushort’ rather than its struct type keyword, but either will be fine. Notice the code below that assigns short variables to 0. To use the short struct, you must use “System.Int16”.
short a = 0;
System.Int16 b = 0;
ushort c = 0;
System.UInt16 d = 0;
You can just use ‘Int16’ or ‘UInt16’ but you will need to insert “using System;” above namespace.
using System;
namespace GetCoding
{
class Program
{
static void Main()
{
short a = 0;
Int16 b = 0;
ushort c = 0;
UInt16 d = 0;
}
}
}
By using “short” you make your code easier, simpler and can be classed as the standard. However you could also use ‘var’ variable keyword but you would need to cast as short, due to the standard number being an integer type.
{
short a = 0;
var b = 0; // This defaults to int (Int32).
var c = (short)0; // 'var' is of type 'short' due to casting
var d = new short(); // This is byte with default value of 0
}
The above is the same for ‘ushort’ type.
Properties of short and ushort
There are two properties that you can use, these are MaxValue and MinValue.
Type | MinValue | MaxValue |
short | -32,768 | 32,767 |
ushort | 0 | 65,535 |
Code example:
using System;
namespace GetCoding
{
class Program
{
static void Main()
{
short shortMinValue = short.MinValue;
short shortMaxValue = short.MaxValue;
ushort ushortMinValue = ushort.MinValue;
ushort ushortMaxValue = ushort.MaxValue;
Console.WriteLine("short MinValue:" + shortMinValue.ToString());
Console.WriteLine("short MaxValue:" + shortMaxValue.ToString());
Console.WriteLine("ushort MinValue:" + ushortMinValue.ToString());
Console.WriteLine("ushort MaxValue:" + ushortMaxValue.ToString());
Console.ReadKey();
}
}
}
Output produced from above code sample:
As you can see MaxValue assigns the max that the variable type can hold, and MinValue outputs the smallest value.
Overflow
By default, overflow for short types are disabled. See Overflow Exception.