Open In App

C# UInt16 Struct

Last Updated : 31 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C#, the UInt16 struct, defined under the System namespace, represents a 16-bit unsigned integer, commonly referred to as the ushort data type. It does not support negative values and provides a range from 0 to 65,535. The UInt16 struct inherits the ValueType class, which further inherits the Object class.

  • UInt16 Range: It ranges from 0 to 65535.
  • Operations: Converting the value of an instance to its string representation, converting a string representation of a number to an instance.
  • This is useful when the need to store unsigned values does not allocate space for negative values, it provides a higher range.

Fields

  • MaxValue: It represents the largest possible value of UInt16. This field is constant.
  • MinValue: It represents the smallest possible value of UInt16. This field is constant

Example:

C#
// C# program to illustrate the fields of UInt16 struct
using System;

class Geeks
{
    static public void Main()
    {
        // Unsigned 16-bit integer
        ushort val = 295;

        // Checking the unsigned integer
        if (val.Equals(UInt16.MinValue))
            Console.WriteLine("Equal to MinValue..!");
        else if (val.Equals(UInt16.MaxValue))
            Console.WriteLine("Equal to MaxValue");
        else
            Console.WriteLine("Not equal");
    }
}

Output
Not equal

Methods

Method

Description

CompareTo()

Compares the current instance to a specified object or UInt16 and returns an indication of their relative values.

Equals()

Returns a value which shows whether the current instance is equal to a specified object or UInt16.

GetHashCode()

Returns the hash code for this instance.

GetTypeCode()

Returns the TypeCode for value type UInt16.

Parse()

Converts the string representation of a number to its 16-bit unsigned integer equivalent

ToString()

Converts the numeric value of this instance to its equivalent string representation.

TryParse()

Converts a number in string form to a 16-bit unsigned integer, indicating success or failure.

Example: Using GetHashCode() Method

C#
// C# program to illustrate how to get the hash 
// code of a 16-bit Unsigned integer
using System;

class Geeks
{
    static public void Main()
    {
        // UInt16 variable
        ushort val = 545;

        // Get the hash code using GetHashCode Method
        int res = val.GetHashCode();

        Console.WriteLine("Hash code of val: {0}", res);
    }
}

Output
Hash code of val: 545

Next Article
Article Tags :

Similar Reads