Essentially I shouldn’t be doing this for two reasons:
- It is probably losing data since a decimal is not a positive integer. It may be, but there are no guarantees. Of course, you can check before and only after you are sure that the conversion will be successful to do, but it does not seem to be making sure of this. The negative would even generate error.
- The use of unmarked types should be restricted to the low level, to communicate with the operating system or other language that requires the data to be so. There are a number of implications to its use that are not easy to get right. Only use it when you have complete mastery of computation.
You probably have a better solution to the problem. But if you still want to insist on this you need to answer a question:
How do you expect to convert a data to a decimal part? You should truncate or round?
If you need to round at your own discretion you have to do it in the hand first.
You can have it converted with the right method, the way you were doing, or you can use a simple cast which in this case works well, as long as you want the truncation or know that you can never have a decimal part value.
using static System.Console;
using static System.Convert;
public class Program {
public static void Main() {
var x = 15.7M;
WriteLine(ToUInt16(x));
WriteLine((ushort)x);
}
}
Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.