title: How do I write overloaded functions in VB.NET that will all use the same core code?
body: <p>I want to write two overloaded functions in VB.NET.</p>
  
  <p>Most of the logic in the two functions will be the same so I don't want to just duplicate the entire function for the two overloads.</p>
  
  <p>I could achieve this by having each overloaded function call another function (that contains the core logic) with optional parameters, like this:</p>
  
  <pre><code>Public Overloads Function GetLocationDetails(ByVal countryId As Integer) As LocationInfo
      Return _GetLocationDetails(countryId)
  End Function
  
  Public Overloads Function GetLocationDetails(ByVal countryId As Integer, ByVal stateId As Integer) As LocationInfo
      Return _GetLocationDetails(countryId, stateId)
  End Function
  
  ' This is the function providing the core logic for the two overloaded functions
  Private Function _GetLocationDetails(ByVal countryId As Integer, Optional ByVal stateId As Integer = 0) As LocationInfo
      Dim returnVal As New LocationInfo
  
      Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("myConnectionString").ConnectionString)
          Using cmd As SqlCommand = con.CreateCommand
              cmd.CommandText = "SELECT name, population FROM locations WHERE countryId = @countryId"
              cmd.Parameters.Add(New SqlParameter("@countryId", countryId))
  
              ' If there is a stateId, this function was called by the overloaded function that has a stateId parameter, so add that to the query
              If stateId &lt;&gt; 0 Then
                  cmd.CommandText &amp;= " AND stateId = @stateId"
                  cmd.Parameters.Add(New SqlParameter("@stateId", stateId))
              End If
  
              con.Open()
              Using dr As SqlDataReader = cmd.ExecuteReader
                  If dr.Read Then
                      returnVal.Name = dr("name")
                      returnVal.Population = dr("population")
                  End If
              End Using
          End Using
      End Using
  
      Return returnVal
  End Function
  
  Public Class LocationInfo
      Public Name As String
      Public Population As Integer
  End Class
  </code></pre>
  
  <p>But using optional parameters doesn't seem very elegant and seems to negate the whole purpose of overloading the functions in the first place.</p>
  
  <p>Is there a better way?</p>