C# Convert ToByte(Object)
Description
Convert ToByte(Object)
converts the value of the specified
object to an 8-bit unsigned integer.
Syntax
Convert.ToByte(Object)
has the following syntax.
public static byte ToByte(
Object value
)
Parameters
Convert.ToByte(Object)
has the following parameters.
value
- An object that implements the IConvertible interface, or null.
Returns
Convert.ToByte(Object)
method returns An 8-bit unsigned integer that is equivalent to value, or zero if value is
null.
Example
The following example uses the ToByte(Object) method to convert an array of objects to Byte values.
// w w w . ja v a2s . c o m
using System;
public class MainClass{
public static void Main(String[] argv){
object[] values = { true, -12, 123, 321, 'x', "104", "103.0", "-1",
"1.00e2", "One", 1.00e2};
byte result;
foreach (object value in values)
{
try {
result = Convert.ToByte(value);
Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
value.GetType().Name, value,
result.GetType().Name, result);
}
catch (OverflowException)
{
Console.WriteLine("The {0} value {1} is outside the range of the Byte type.",
value.GetType().Name, value);
}
catch (FormatException)
{
Console.WriteLine("The {0} value {1} is not in a recognizable format.",
value.GetType().Name, value);
}
catch (InvalidCastException)
{
Console.WriteLine("No conversion to a Byte exists for the {0} value {1}.",
value.GetType().Name, value);
}
}
}
}
The code above generates the following result.