Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
byte
sbyte
difference
communitycreator

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

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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());
}
}
Create byte and sbyte variables in C#

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());
}
}
Initializing a byte and sbyte with values above or below their range will throw an error

RELATED TAGS

c#
byte
sbyte
difference
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring