Using Convert.ToByte to convert value to byte
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);
}
}
}
}
Related examples in the same category