Return value of a function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pankajit09
    Contributor
    • Dec 2006
    • 296

    Return value of a function

    I get the below warning :

    Code:
    Warning	1	Function 'exportToCSV' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.	C:\Documents and Settings\cxvngh\My Documents\Visual Studio 2008\Projects\OutCre\OutCre\Module1.vb	193	5	OutCre
    To solve it I put a return statement "Return 1" in the code.

    Is it the right way ?
  • PRR
    Recognized Expert Contributor
    • Dec 2007
    • 750

    #2
    Your function does not return on all code paths
    Code:
    public static int Call()
            {
                int i = 90;
    
                if (i > 90)
                {
                    return i;
                }
    // Here we need a default return... 
            }
    
    
    public static int Call()
            {
                int i = 90;
    
                if (i > 90)
                {
                    return i;
                }
    
                else
                {
                    return -1;
                }
            }

    Comment

    • Frinavale
      Recognized Expert Expert
      • Oct 2006
      • 9749

      #3
      Just in case you don't understand what DeepBlue has said I'll restate it.

      If you are creating a method that does not return anything then you should define it as a Sub.

      For example, the following method definition is of a method that does not return a value:
      Code:
      Private Sub ExportToCSV()
        'Your code goes here
      End Sub
      If your method returns something (say the path to the file you created) then you would define it as a Function.

      For example, the following method returns a String:
      Code:
      Private Function ExportToCSV() As String
        Dim path As String = "C:\MyFolder\MyCVSFileName.cvs"
      
        'Your code goes here
        
         return path
      End Function

      You are getting that message because your Function is not returning a value.
      If you have an "if" statement in your function that returns a value, you must also have a "default" return value for the function. In other words your function must always return something if it's a function.

      For example, the following will cause an error because there is no default return value:
      Code:
      Private Function ExportToCSV() As String
        Dim path As String = "C:\MyFolder\MyCVSFileName.cvs"
        If someBoolean = True Then
          return path
        End If
      
        'Your code goes here
        
      End Function
      It is advisable to always have 1 return statement in a method just to keep things less confusing and to avoid this type of error.


      -Frinny

      Comment

      Working...