string strValue = "65535"; ushort result; if (UInt16.TryParse(strValue, out result)) { Console.WriteLine("The converted number is {0}.", result); } else { Console.WriteLine("The string could not be converted to a UInt16."); }
string strValue = "100000"; ushort result; if (UInt16.TryParse(strValue, out result)) { Console.WriteLine("The converted number is {0}.", result); } else { Console.WriteLine("The string could not be converted to a UInt16."); }This example attempts to convert the string "100000" to its 16-bit unsigned integer equivalent. Since the value is outside the range of a UInt16, the conversion will fail, and the output will be "The string could not be converted to a UInt16." The System.UInt16.TryParse method is part of the System namespace and does not require any additional package library.