C# Sbyte Type

Sbyte illustration

Sbyte is one signed byte. This signed byte type in the C# language represents a small integer that can be negative or positive. It is 8 bits or 1 byte and it stores integers between -128 and 127. It is less commonly used than other numeric types.

Byte Type Keywords
System.SByte information

sbyte.MinValue = -128
sbyte.MaxValue =  128

Example

Note

First, this program uses an sbyte local variable and tests and increments it. It also prints the size in bytes of the sbyte; the default value of the sbyte; the minimum value it can store; the maximum value; the Type associated with it; and the TypeCode associated with its type.

Program that uses sbyte type [C#]

using System;

class Program
{
    static void Main()
    {
	sbyte val = 1; // Local variable.

	Console.WriteLine("val:     {0}", val);
	Console.WriteLine("sizeof:  {0}", sizeof(sbyte));
	Console.WriteLine("default: {0}", default(sbyte));
	Console.WriteLine("min:     {0}", sbyte.MinValue);
	Console.WriteLine("max:     {0}", sbyte.MaxValue);
	Console.WriteLine("type:    {0}", val.GetType());
	Console.WriteLine("code:    {0}", val.GetTypeCode());
	if (val == 1) // Test.
	{
	    Console.WriteLine("1:       {0}", true);
	}
	val++; // Increment.
	Console.WriteLine("val:     {0}", val);
    }
}

Output

val:     1
sizeof:  1
default: 0
min:     -128
max:     127
type:    System.SByte
code:    SByte
1:       True
val:     2

Further description. You can see that the program's output is pretty predictable. You can assign and increment sbytes just like any other value type. An unassigned sbyte on the heap will be initialized to 0. The sizeof operator returns 1, meaning the sbyte is truly just a single byte. You can test sbytes using selection statements such as if and switch.

If Statement Switch Statement

Why?

Question and answer

The sbyte type doesn't really provide any low-level functionality that the byte type doesn't. However, it can improve interoperability with certain other libraries (DLLs) that assume signed bytes. However, because both sbyte and byte represent 8 bits, you can store the bits in either type with no data loss. If a program uses signed bytes, though, the data will make more sense if you treat one of the bits as a sign bit by using sbyte.

Summary

The C# programming language

The sbyte type is not useful for most purely managed programs, but it can be handy if your byte representation happens to include a sign bit. As a value type, the sbyte is allocated upon the evaluation stack when used as a local variable. It can represent numbers from -128 to 127, and can be manipulated just like other integer types.

Number Examples
.NET