Re: Function Warning - Null Reference
- From: Tom Shelton <tom_shelton@xxxxxxxxxxxxxxxxxx>
- Date: Thu, 11 Jan 2007 19:40:47 -0600
On 2007-01-12, Terry <news-grps@xxxxxxxxxxxxxxxxxxxxxxxx> wrote:
I am getting the following warning for the below function. I understand what
it means but how do I handle a null reference? Then how do I pass the
resulting value?
Regards
Warning 1 Function 'Dec2hms' doesn't return a value on all code paths. A
null reference exception could occur at run time when the result is used.
G:\Project Development\Visual Studio
2005\Projects\Ascension\Ascension\SwephConversions.vb 64 3 Ascension
' Convert decimal hours to hours/minutes/seconds
Public Function Dec2hms(ByVal x As Decimal) As String
Dim hh As Int32, mm As Int32, ss As Decimal, remainder As Decimal
'Dim x a decimal, hh as integer
hh = CType(x, Integer)
remainder = (x - hh)
mm = CType((remainder * 60), Integer)
remainder = ((remainder * 60) - mm)
ss = Int(remainder * 60)
remainder = ((remainder * 60) - ss)
If remainder >= 0.5 Then
ss = ss + 1
Else
ss = ss
End If
hms = hh & "h " & mm & "m " & ss & "s"
End Function
The problem is that you are not returning a value at all that I can see.
Which means that the value of the function will always be a null reference.
There are two, ways to return a value from a function in vb.net. One, is the
same as the old vb way - and that is to assign the value to the function name:
Public Function Dec2hms As String
....
Dec2hms = hh & "h " & mm & "m " & ss & "s"
End Function
The other, prefered way is to use the Return statment:
Public Function Dec2hms As String
....
Return hh & "h " & mm & "m " & ss & "s"
End Function
Now, to avoid these kind of warnings, you just need to make sure that there is
a return along all normal code paths.... I personally like to structure code
so that there is only one exit point, so that often leads to code that looks
something like:
Public Function SomeFunc As Boolean
' i chose to default to a failure, but that
' can change based on what is easier and makes
' more sense for the method
Dim success As Boolean = False
' do cool stuff that might change the value of success
Return success
End Function
HTH,
--
Tom Shelton
.
- Follow-Ups:
- Re: Function Warning - Null Reference
- From: Terry
- Re: Function Warning - Null Reference
- References:
- Function Warning - Null Reference
- From: Terry
- Function Warning - Null Reference
- Prev by Date: Re: Comment Blocks in VB
- Next by Date: Re: Form inheritance problem
- Previous by thread: Re: Function Warning - Null Reference
- Next by thread: Re: Function Warning - Null Reference
- Index(es):
Relevant Pages
|