Byte Struct in C#


Byte Struct in C# represents an 8-bit unsigned integer. Following are the fields −

Sr.noField & Description
1MaxValue
Represents the largest possible value of a Byte. This field is constant.
2MinValue
Represents the smallest possible value of a Byte. This field is constant.

Following are some of the methods −

Sr.noField & Description
1CompareTo(Byte)
Compares this instance to a specified 8-bit unsigned integer and returns an indication of their relative values.
2CompareTo(Object)
Compares this instance to a specified object and returns an indication of their relative values.
3Equals(Byte)
Returns a value indicating whether this instance and a specified Byte object represent the same value.
4Equals(Object)
Returns a value indicating whether this instance is equal to a specified object.
5GetHashCode()
Returns the hash code for this instance.
6GetTypeCode().
Returns the TypeCode for value type Byte.

Example

 Live Demo

using System;
public class Demo {
   public static void Main() {
      string str = "186";
      try {
         byte val = Byte.Parse(str);
         Console.WriteLine(val);
      }
      catch (OverflowException) {
         Console.WriteLine("Out of range of a byte.", str);
      }
      catch (FormatException) {
         Console.WriteLine("Out of range of a byte.", str);
      }

   }
}

Output

This will produce the following output −

186

Example

Let us see another example −

 Live Demo

using System;
public class Demo {
   public static void Main() {
      byte[] arr = { 0, 10, 50, 90, 100, 150 };
      foreach (byte b in arr) {
         Console.Write(" ", b.ToString());
         Console.Write(b.ToString("D4") + " ");
         Console.WriteLine(b.ToString("X4"));
      }
   }
}

Output

This will produce the following output −

 0000   0000
 0010   000A
 0050   0032
 0090   005A
 0100   0064
 0150   0096

Updated on: 11-Dec-2019

177 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements