Link to home
Start Free TrialLog in
Avatar of DaveMon
DaveMonFlag for United States of America

asked on

VB2005 Express "Function does not return a value"?

Hello Experts,  I need help fixing a apperantly harmless error.....the app still runs  but  I get this warning on two functions

Function 'GetString' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.


CODE
************************
    Public Function GetString(ByVal Section As String, _
      ByVal Key As String, ByVal [Default] As String) As String
        ' Returns a string from your INI file
        Dim intCharCount As Integer
        Dim objResult As New System.Text.StringBuilder(256)
        intCharCount = GetPrivateProfileString(Section, Key, _
           [Default], objResult, objResult.Capacity, strFilename)
        If intCharCount > 0 Then GetString = _
           Left(objResult.ToString, intCharCount)
    End Function
***************************

thanks  all  for your  assistance
ASKER CERTIFIED SOLUTION
Avatar of vadim63
vadim63
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Public Function GetString(ByVal Section As String, _
      ByVal Key As String, ByVal [Default] As String) As String
        ' Returns a string from your INI file
        Dim intCharCount As Integer
        Dim objResult As New System.Text.StringBuilder(256)
        intCharCount = GetPrivateProfileString(Section, Key, _
           [Default], objResult, objResult.Capacity, strFilename)
        If intCharCount > 0 Then

          Return Left(objResult.ToString, intCharCount)
else return "something"

    End Function
Avatar of pauljk1619
pauljk1619

Because your return statement only occurs if intCharCount > 0.....   Add an else with a different return value....  Otherwise if intCharCount is not > 0, you could get a null exception error.  


        If intCharCount > 0 Then
          Return Left(objResult.ToString, intCharCount)
        else
           Return ""
        end if
Avatar of Mike Tomlinson
Sometimes its nice to declare a variable specifically for the return and then return that variable:

    Public Function GetString(ByVal Section As String, _
      ByVal Key As String, ByVal [Default] As String) As String

        Dim retString As String = "" ' or use Nothing instead of ""

        ' Returns a string from your INI file
        Dim intCharCount As Integer
        Dim objResult As New System.Text.StringBuilder(256)
        intCharCount = GetPrivateProfileString(Section, Key, _
           [Default], objResult, objResult.Capacity, strFilename)
        If intCharCount > 0 Then
          retString = Left(objResult.ToString, intCharCount)
        End If

        Return retString
    End Function
Avatar of DaveMon

ASKER

thanks to everyone for their assistance on this post !!!
Dave