Lesson 2.5

short data type C# - programming example


Objective

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

What is short Data Types in C#?

"short data type is 16-bit signed integer data type which stores value between -32,768 to 32,767. It is used for mostly storing numeric value."

TypeRangeSize.Net Framework type
short-32,768 to 32,768signed 16-bit integerSystem.Int16

Declaration and Initialization

You can declare short data type as follow:

		  
  short num1=3290;
		  

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

Constant value '40000' cannot be converted to a 'short'

Programming Example

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

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


		  

Output

50
_

Conversion

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

Incorrect Method
  result = num1 + num2;
		  

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


Correct Method
  result = (short)(num1 + num2); //Correct: Explicit Conversion
		  

Passing short value as parameter

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

Programming Example

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

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

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

        public static void ShowNumber(short 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

short is signed 16-bit integer type data type which stores value between -32,768 to 32,767. It is mostly used for storing numeric value. In the next chapter we will discuss on ushort data type.

BackNext