ushort (C# Reference)


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

The ushort keyword indicates an integral data type that stores values according to the size and range shown in the following table.

TypeRangeSize.NET Framework type
ushort0 to 65,535Unsigned 16-bit integerSystem.UInt16

You can declare and initialize a ushort variable such as this example:

ushort myShort = 65535;  

In the previous declaration, the integer literal 65535 is implicitly converted from int to ushort. If the integer literal exceeds the range of ushort, a compilation error will occur.

A cast must be used when you call overloaded methods. Consider, for example, the following overloaded methods that use ushort and int parameters:

public static void SampleMethod(int i) {}  
public static void SampleMethod(ushort s) {}  

Using the ushort cast guarantees that the correct type is called, for example:

// Calls the method with the int parameter:  
// Calls the method with the ushort parameter:  

There is a predefined implicit conversion from ushort to int, uint, long, ulong, float, double, or decimal.

There is a predefined implicit conversion from byte or char to ushort. Otherwise a cast must be used to perform an explicit conversion. Consider, for example, the following two ushort variables x and y:

ushort x = 5, y = 12;  

The following assignment statement will produce a compilation error, because the arithmetic expression on the right side of the assignment operator evaluates to int by default.

ushort z = x + y;   // Error: conversion from int to ushort  

To fix this problem, use a cast:

ushort z = (ushort)(x + y);   // OK: explicit conversion   

It is possible though to use the following statements, where the destination variable has the same storage size or a larger storage size:

int m = x + y;  
long n = x + y;  

Notice also that there is no implicit conversion from floating-point types to ushort. For example, the following statement generates a compiler error unless an explicit cast is used:

// Error -- no implicit conversion from double:  
ushort x = 3.0;   
// OK -- explicit conversion:  
ushort y = (ushort)3.0;  

For information about arithmetic expressions with mixed floating-point types and integral types, see float and double.

For more information about implicit numeric conversion rules, see the Implicit Numeric Conversions Table.

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

C# Reference
C# Programming Guide
C# Keywords
Integral Types Table
Built-In Types Table
Implicit Numeric Conversions Table
Explicit Numeric Conversions Table