Convert value to byte in CSharp

Description

The following code shows how to convert value to byte.

Example


  /*from  ww w  . j  a  va 2  s .  co m*/
  
  
     

using System;

public class Example
{
   public static void Main()
   {
        int[] numbers = { Int32.MinValue, -1, 0, 121, 128,340, Int32.MaxValue };
        byte result;
        foreach (int number in numbers)
        {
           try {
              result = Convert.ToByte(number);
              Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", 
                                number.GetType().Name, number, 
                                result.GetType().Name, result);
           }                     
           catch (OverflowException) {
              Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", 
                                number.GetType().Name, number);
           }
        }
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var