Reputation: 493
I got the warning: "Function doesn't return a value on all codepaths" for the following code:
Function Test() As Boolean
Dim X As Integer = 5
If X = 10 Then
Return True
End If
End Function
I do understand that I won't return a value in all code paths, since the If statement requires X = 10
in order to access Return
. But since the default value when creating a function is False, i expect that to be returned when the criteria isn't filled. So the function in reality does return a value on all code paths.
I assume that it is a bad practice to rely on the default value of the function, especially since the function is created to return a value in the first place. Can someone shed a light on the topic and help resolve my confusion?
I can remove the warning by changing the code to:
Function Test() As Boolean
Dim X As Integer = 5
If X = 10 Then
Return True
Else
Return False
End If
End Function
Or
Function Test() As Boolean
Dim X As Integer = 5
Return (X = 10)
End Function
Upvotes: 3
Views: 113
Reputation: 460108
since the default value when creating a function is False, i expect that to be returned when the criteria isn't filled
No, that's a wrong expectation. The reason why .NET doesn't do this is obvious:
it's a way to prevent you from careless mistakes. Often you simply overlook that your code paths don't return a value, so if the method would assume that you want to return False
then it would hide a bug.
So it forces you to provide the return value yourself.
In VB.NET you can also use Exit Function
, then you are returning the default value for that type.
MSDN:
If you use
Exit Function
without assigning a value to name, the procedure returns the default value for the data type that's specified in returntype. If returntype isn't specified, the procedure returns Nothing, which is the default value for Object.
But in my opinion this is bad practice and only there to be downwards compatible with VB6.
There is another way to leave a function without returning anything: if you throw an exception.
So the warning is a way to tell you that you should rethink your logic, it just reminds you that you might have forgotten a case. A final Return something
at the end doesn't hurt you anyway:
Function Test() As Boolean
Dim X As Integer = 5
If X = 10 Then Return True
Return False
End Function
Upvotes: 1