sbyte (C# Reference)

The sbyte keyword indicates an integral type that stores values according to the size and range shown in the following table.

Type

Range

Size

.NET Framework type

sbyte

-128 to 127

Signed 8-bit integer

System.SByte

Literals

You can declare and initialize an sbyte variable in this manner:

sbyte sByte1 = 127;

In the previous declaration, the integer literal 127 is implicitly converted from int to sbyte. If the integer literal exceeds the range of sbyte, a compilation error will occur.

A cast must be used when calling overloaded methods. Consider, for example, the following overloaded methods that use sbyte and int parameters:

public static void SampleMethod(int i) {}
public static void SampleMethod(sbyte b) {}

Using the sbyte cast guarantees that the correct type is called, for example:

// Calling the method with the int parameter:
SampleMethod(5);
// Calling the method with the sbyte parameter:
SampleMethod((sbyte)5);

Conversions

There is a predefined implicit conversion from sbyte to short, int, long, float, double, or decimal.

You cannot implicitly convert nonliteral numeric types of larger storage size to sbyte (see Integral Types Table (C# Reference) for the storage sizes of integral types). Consider, for example, the following two sbyte variables x and y:

sbyte x = 10, y = 20;

The following assignment statement will produce a compilation error, because the arithmetic expression on the right side of the assignment operator evaluates to int by default.

sbyte z = x + y;   // Error: conversion from int to sbyte

To fix this problem, cast the expression as in the following example:

sbyte z = (sbyte)(x + y);   // OK: explicit conversion

It is possible though to use the following statements, where the destination variable has the same storage size or a larger storage size:

sbyte x = 10, y = 20;
int m = x + y;
long n = x + y;

Notice also that there is no implicit conversion from floating-point types to sbyte. For example, the following statement generates a compiler error unless an explicit cast is used:

sbyte x = 3.0;         // Error: no implicit conversion from double
sbyte y = (sbyte)3.0;  // OK: explicit conversion

For information about arithmetic expressions with mixed floating-point types and integral types, see float and double.

For more information about implicit numeric conversion rules, see the Implicit Numeric Conversions Table (C# Reference).

C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 1.3 Types and Variables

  • 4.1.5 Integral Types

See Also

Concepts

C# Programming Guide

Reference

C# Keywords

Integral Types Table (C# Reference)

Built-In Types Table (C# Reference)

Implicit Numeric Conversions Table (C# Reference)

Explicit Numeric Conversions Table (C# Reference)

SByte

Other Resources

C# Reference