C Sharp (C#) Byte and sbyte Data Type


Byte datatype has a range from 0 to 255 and can be assigned as below :
byte b = 255

In the preceding declaration, the integer literal 255 is implicitly converted from int to byte. If the integer literal exceeds the range of byte, a compilation error will occur. There is a predefined implicit conversion from byte to short, ushort, int, unit, long, ulong, float, double, decimal.


Similarly an sbyte is a signed byte which has a limit from -128 to +127. The following example shows the usage of both signed and unsigned byte when values are within and outside the limits.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            byte a = 100;
            byte b = 100;
            byte c = (byte)(a + b);
            Console.WriteLine("The addition of two unsigned byte numbers {0} and {1} is : {2}", a, b, c);
            Console.ReadLine();

            sbyte d = 100;
            sbyte e = 100;
            sbyte f = (sbyte)(d + e);
            Console.WriteLine("The addition of two signed byte numbers {0} and {1} is : {2}", d, e, f);
            Console.ReadLine();
        }
    }
}

Output :

C Sharp Datatypes Home Page

No comments: