Lesson 2.4

sbyte data type C# - programming example


Objective

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

What is sbyte Data Types in C#?

"sbyte data type is integral type which stores value between -128 to 127. It is derived from System.SByte class and it is signed 8-bit integer in size."

TypeRangeSize.Net Framework type
sbyte-128 to 127signed 8-bit integerSystem.SByte

How to declare and initialize sbyte data type in c# ?

You can declare sbyte data type in following manner.

		  
  sbyte Num1=125;
		  

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

Constant value '129' cannot be converted to a 'sbyte'

Programming Example

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

namespace sbyte_data_type
{
    class Program
    {
        static void Main(string[] args)
        {
            sbyte num1 = 10, num2=20, result;
            result = (sbyte)(num1 + num2); //Convert to sbyte type
            Console.WriteLine(result);
            Console.ReadLine();
        }
    }
}


		  

Output

30
_

Conversion

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

Incorrect Method
  result = num1 + num2;
		  

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


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

Passing sbyte value as parameter

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

Programming Example

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

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

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

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

sbyte is signed 8-bit integer data type which stores value between -128 to 127. When solving different types of programming challenges in c sharp (C#) you need to use sbyte data type. In the next chapter we will learn about short data type.

BackNext