Suppose option Strict On; a and b – Integers
Dim mySingle as Single = a / b ' implicit conversion error
Solution A)
Dim mySingle as Single = CSng(a / b) ' CSng
Solution B)
Dim mySingle as Single = a * 1F / b ' x 1F
What solution is preferable?
What solution to take if performance is important?
For readability and revealing intent, I would go with A:
Using A, you are clearly saying, I know the calculation returns a different type and that’s what I want.
As for performance – I ran a quick micro-benchmark testing 1 million iterations for each and the difference was in the millisecond to sub-millisecond level, with a very slight advantage to
CSing. Don’t worry about performance for this kind of conversions (of course, you need to test this on your own).Benchmark code: