Lesson 2.3

byte data type c# with programming examples


Objective

What is byte data type?
How to declare and initialize byte data type?
Conversion of byte variable
Error and resolution of byte data type

What is byte Data Types in C#?

"byte is very small size data type which takes only 8 bit in memory. It is used for storing small numeric value between 0 to 255."

For example, If you are asking age of user then byte data type is most suitable but if you are doing some arithmetic operation as adding or multiplying then byte data type is not suitable.


TypeRangeSize.Net Framework type
byte0 to 255Unsigned 8-bit integerSystem.Byte

View all the Method and Fields of byte

How to declare and initialize byte data type in c# ?

You can declare and initialize byte variable as follow:

		  
  byte byteNum1=10, byteNum2=12, byteResult=25;
		  

Note:You cannot store value larger than 255 in a byte variable otherwise you will get following compilation error:

Constant Value ‘256’ cannot be converted to a 'byte'


Programming Example of byte variable

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

namespace Chapter_2_byte
{
    class Program
    {
        static void Main(string[] args)
        {
            byte byteNum1 = 10, byteNum2 = 12, byteResult;
           
            byteResult = (byte)(byteNum1 + byteNum2);
            Console.WriteLine(byteResult);
            Console.ReadLine();
        }
    }
}

		  

Output

22
_

Conversion

The arithmetic operation at right hand side is considered int by default. So, the following line gives compile time error message.

		  
  byteResult = byteNum1 + byteNum2;
		  

Error: Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)


You need to cast right hand side to fix this problem. Casting is a technique to convert one data type into another data type.

Learn more about Casting and Conversion.
		  
  byteResult = (byte)(byteNum1 + byteNum2);
		  

It is best habbit to cast or convert data into respective datatype everywhere. It will save you from unnecessary runtime errors and makes your code more robust.

Summary

In this chapter, we have learned about byte data type. byte data type is a small size data type which is used for storing small values. Whenever you write a program, it is recommended to select best match data type to keep memory free at runtime. In the next chapter, we will learn about sbyte data type.

BackNext