public void TestUInt16ToByteNullable() { // Test conversion of source type minimum value UInt16 source = UInt16.MinValue; Assert.IsInstanceOfType(source, typeof(UInt16)); Byte?result = source.ToByteNullable(); Assert.AreEqual((byte)0, result); Assert.IsInstanceOfType(result, typeof(Byte)); // Test conversion of source type value 42 to target type source = (ushort)42; Assert.IsInstanceOfType(source, typeof(UInt16)); result = source.ToByteNullable(); Assert.AreEqual((byte)42, result); Assert.IsInstanceOfType(result, typeof(Byte)); // Test conversion of source type maximum value source = UInt16.MaxValue; Assert.IsInstanceOfType(source, typeof(UInt16)); result = source.ToByteNullable(); // Here we would expect this conversion to fail (and return null), // since the source type's maximum value (65535) is greater than the target type's maximum value (255). Assert.IsNull(result); }
/// <summary> /// Converts this UInt16 to Byte or returns the specified default value /// </summary> /// <returns>This UInt16 converted to Byte</returns> /// <remarks> /// Source type: UInt16 /// Min value: 0 /// Max value: 65535 /// /// Target type: Byte /// Min value: 0 /// Max value: 255 /// </remarks> public static Byte ToByteOrDefault(this UInt16 thisUInt16, Byte defaultValue = default(Byte)) { return(thisUInt16.ToByteNullable().GetValueOrDefault(defaultValue)); }