C# Keywords Tutorial Part 76: short

C# Keywords Tutorial Part 76: short

Popular programming language C# is used a lot in the creation of applications. It offers developers a variety of tools to help them write effective and efficient code. The “short” keyword, which is used to declare a variable of type short, is one of these characteristics. The “short” keyword in C# will be covered in this blog article along with some sample code.

The “short” Keyword in C#

A short-type variable is declared with the keyword “short”. A 16-bit signed integer, the short data type may hold values between -32,768 and 32,767. When working with little numbers that don’t need the entire 32-bit integer range or when memory use is an issue, the “short” keyword is frequently utilized.

Here’s an example of how to declare a variable of type short using the “short” keyword:

short myShortVariable = 1000;

In the above example, we have declared a variable named “myShortVariable” of type short and assigned it a value of 1000.

Let’s look at some more examples to understand how the “short” keyword can be used in C#.

Example 1: Adding Two Short Variables

short firstNumber = 32760;
short secondNumber = 5;
short result = (short)(firstNumber + secondNumber);
Console.WriteLine("Result: " + result);

In the above example, we have declared two variables of type short named “firstNumber” and “secondNumber”. We have then added these two variables and stored the result in a variable named “result”. Since we are adding two short variables, the result may exceed the range of short, so we need to explicitly cast it back to a short using “(short)”.

Example 2: Converting a String to Short

string numberString = "2000";
short result = short.Parse(numberString);
Console.WriteLine("Result: " + result);

In the above example, we have declared a string variable named “numberString” and assigned it a value of “2000”. We have then used the “short.Parse()” method to convert the string to a short and stored the result in a variable named “result”. This is useful when working with user input, where the input is received as a string, and we need to convert it to a short.

Example 3: Using Short in a Loop

short[] numbers = { 10, 20, 30, 40, 50 };
short sum = 0;
for (int i = 0; i < numbers.Length; i++)
{
    sum += numbers[i];
}
Console.WriteLine("Sum: " + sum);

In the above example, we have declared an array of short named “numbers” and initialized it with some values. We have then declared a variable named “sum” of type short and assigned it a value of 0. We have then used a for loop to iterate over the elements of the “numbers” array and added them to the “sum” variable. Finally, we have printed the value of the “sum” variable.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *