TheDeveloperBlog.com


C# Sbyte Type

Sbyte is one signed byte. This signed byte type 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
System.SByte information

sbyte.MinValue = -128
sbyte.MaxValue =  128


Example. This program first tests and increments a sbyte local variable. It next prints the size in bytes of the sbyte. It prints the default value of the sbyte. It shows the minimum and maximum values.

And: The program uses logic to return the Type and TypeCode associated with the sbyte type.

C# program that uses sbyte type

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

The output is 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.

Tip: You can test sbyte variables using selection statements such as if and switch.

IfSwitch

Discussion. The sbyte type doesn't 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.

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 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.

And: Sbyte can represent numbers from -128 to 127, and can be manipulated just like other integer types.