What is the difference between byte and sbyte in C#?

Overview

In C#, the sbyte and sbyte data types, used for byte type data. While byte is used to store unsigned byte data, which works only on positive values from 0–255, sbyte works on both negative and positive between -128 and 127.

Syntax

byte variable
sbyte variable
Syntax for byte and sbyte in C#

Parameters

variable: This is the variable we want to create as a byte or sbyte.

Example

using System;
class HelloWorld
{
static void Main()
{
// create byte variables from 0-255
byte b1 = 25;
byte b2 = 100;
byte b3 = 255;
// create sbyte variables from -128 - 127
sbyte sb1 = -12;
sbyte sb2 = 12;
sbyte sb3 = 100;
// print values and data types
Console.WriteLine("{0} is {1}", b1, b1.GetTypeCode());
Console.WriteLine("{0} is {1}", b2, b2.GetTypeCode());
Console.WriteLine("{0} is {1}", b3, b3.GetTypeCode());
Console.WriteLine("{0} is {1}", sb1, sb1.GetTypeCode());
Console.WriteLine("{0} is {1}", sb2, sb2.GetTypeCode());
Console.WriteLine("{0} is {1}", sb3, sb3.GetTypeCode());
}
}

Explanation

  • Line 7–9: We create some byte variables and initialize them.
  • Line 12–14: We create some sbyte variables and initialize them.
  • Line 17–22: We print variable values and types to the console.
Note: If the value used to initialize sbyte or byte is above or below the normal range, an error is thrown.
using System;
class HelloWorld
{
static void Main()
{
// create byte variables from 0-255
byte b1 = 300;
// create sbyte variables from -128 - 127
sbyte sb1 = 200;
// print values and data types
Console.WriteLine("{0} is {1}", b1, b1.GetTypeCode());
Console.WriteLine("{0} is {1}", b1, b1.GetTypeCode());
}
}

Free Resources