public void TestUInt16ToInt16Nullable() { // Test conversion of source type minimum value UInt16 source = UInt16.MinValue; Assert.IsInstanceOfType(source, typeof(UInt16)); Int16?result = source.ToInt16Nullable(); Assert.AreEqual((short)0, result); Assert.IsInstanceOfType(result, typeof(Int16)); // Test conversion of source type value 42 to target type source = (ushort)42; Assert.IsInstanceOfType(source, typeof(UInt16)); result = source.ToInt16Nullable(); Assert.AreEqual((short)42, result); Assert.IsInstanceOfType(result, typeof(Int16)); // Test conversion of source type maximum value source = UInt16.MaxValue; Assert.IsInstanceOfType(source, typeof(UInt16)); result = source.ToInt16Nullable(); // 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 (32767). Assert.IsNull(result); }
/* * SByte to Int16: Method omitted * There is a predefined implicit conversion from SByte to Int16 */ /* * Byte to Int16: Method omitted * There is a predefined implicit conversion from Byte to Int16 */ /// <summary> /// Converts this UInt16 to Int16 or returns the specified default value /// </summary> /// <returns>This UInt16 converted to Int16</returns> /// <remarks> /// Source type: UInt16 /// Min value: 0 /// Max value: 65535 /// /// Target type: Int16 /// Min value: -32768 /// Max value: 32767 /// </remarks> public static Int16 ToInt16OrDefault(this UInt16 thisUInt16, Int16 defaultValue = default(Int16)) { return(thisUInt16.ToInt16Nullable().GetValueOrDefault(defaultValue)); }