Lesson 2.6

ushort data type C# - programming example


Objective

What is ushort data type in c#?
How to declare and initialize
Programming examples
Conversion and Casting

What is ushort Data Types in C#?

"ushort data type is 16-bit unsigned integer data type which stores value between 0 to 65,535. It is used for mostly storing numeric value."

TypeRangeSize.Net Framework type
ushort0 to 65,535unsigned 16-bit integerSystem.UInt16

Declaration and Initialization

You can declare ushort data type as follow:

		  
  ushort num1=4600;
		  

Note:if the value of ushort variable exceed from its range a compilation error occurs:

Constant value '75000' cannot be converted to a 'ushort'

Programming Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ushort_data_type
{
    class Program
    {
        static void Main(string[] args)
        {
            ushort num1, num2, result;
            num1 = 20;
            num2 = 30;
            result = (ushort)(num1 * num2);
            Console.WriteLine(result);
            Console.ReadLine();
        }
    }
}

		  

Output

600
_

Conversion

If you are doing arithmetic operation using ushort variable; it is necessary to convert right side value into ushort data type. for example:

Incorrect Method
  result = num1 * num2;
		  

Compilation Error: Cannot implicitly convert type 'int' to 'ushort'. An explicit conversion exists (are you missing a cast?)


Correct Method
  result = (ushort)(num1 * num2); //Correct: Explicit Conversion
		  

Passing ushort value as parameter

When calling a function which requires ushort value in parameter you must cast value into ushort to avoid compilation error..

Programming Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ushort_data_type
{
    class Program
    {
        static void Main(string[] args)
        {
            ShowNumber((ushort)20); // Correct(√)

            ShowNumber(20); // Incorrect(×)
        }

        public static void ShowNumber(ushort num1)
        {
            Console.WriteLine(num1);
            Console.ReadLine();
        }
    }
}
		  

Output

20
_

It is best habbit to cast or convert data into respective datatype everywhere. It will save you from unnecessary runtime errors and makes your code more robust.

Summary

ushort is unsigned 16-bit integer type data type which stores value between 0 to 65,535. It is mostly used for storing numeric value. In the next chapter we will discuss on Int data type.

BackNext