Recently I was going through several small exercises in development. In one of them I was asked to convert a string to a number in VB .NET respecting the current locale. So I did :
Imports System
Public Module Aplicacion
Public Sub Main()
Console.WriteLine(Numero("Hello World"))
Console.WriteLine(Numero(2))
Console.WriteLine(Numero(.24))
Console.WriteLine(Numero(2.4))
End Sub
Function Numero(input as String) AS Double
Try
return Convert.ToDouble(input)
Catch Ex AS Exception
return 0
End Try
End Function
End Module
The teacher corrected this by telling me that "although it works, the right way is to declare a variable with the same type I am going to return, calculate its value in the body of the function and at the end return this variable".
Is there really any gain in doing that against doing it directly as I did? Maybe some compilation bonus or an improvement in performance?