title: Typecasting generic parameters
body: <p>Using the following code:</p>
  
  <pre><code>Function GetSetting(Of T)(ByVal SettingName As String, ByRef DefaultVal As T) As T
      Return If(Configuration.ContainsKey(SettingName), CType(Configuration(SettingName), T), DefaultVal)
  End Function
  </code></pre>
  
  <p>Yields the following error:</p>
  
  <pre><code>Value of type 'String' cannot be converted to 'T'.
  </code></pre>
  
  <p>Any way I could specify that in all cases, the conversion will indeed be possible (I'm basically getting integers, booleans, doubles and strings).</p>
  
  <p><b>Edit</b>: There seem to be three solutions now:</p>
  
  <ul>
    <li>Using the `ValueAs` function provided by AMissico</li>
    <li>Casting to an `object`, then to `T`, with a check for null values</li>
    <li>Using a `DirectCast` over Convert.ChangeType</li>
  </ul>
  
  <p>Which would you suggest?</p>
  
  <p><b>Edit 2:</b>
  Would this code work?</p>
  
  <pre><code>Function GetSetting(Of T)(ByVal SettingName As String, Optional ByRef DefaultVal As T = Nothing) As T
      Return If(Configuration.ContainsKey(SettingName), ConvertTo(Of T)(Configuration(SettingName)), DefaultVal)
  End Function
  
  Function ConvertTo(Of T)(ByVal Str As String) As T
      Return If(Str Is Nothing Or Str = "", Nothing, CType(CObj(Str), T))
  End Function
  </code></pre>
  
  <p><strong>Edit 3:</strong> [AMJ] Working Code</p>
  
  <pre><code>Function GetSetting(Of T)(ByVal SettingName As String) As T
      Return GetSetting(Of T)(SettingName, Nothing)
  End Function
  Function GetSetting(Of T)(ByVal SettingName As String, ByVal DefaultVal As T) As T
      Dim sValue As String = Configuration(SettingName)
      If Len(sValue) = 0 Then
          Return DefaultVal
      Else
          Return CType(CObj(sValue), T)
      End If
  End Function
  </code></pre>
  
  <hr>
  
  <p>Quick Test Method</p>
  
  <pre><code>Public Sub DoIt()
  
      Me.Configuration.Add("KeyN", Nothing)
      Me.Configuration.Add("KeyE", String.Empty) '""
      Me.Configuration.Add("Key1", "99")
      Me.Configuration.Add("Key2", "1/1/2000")
      Me.Configuration.Add("Key3", "True")
      Me.Configuration.Add("Key4", "0")
  
      Dim o As Object 'using object in order to see what type is returned by methods
  
      o = Value(Of Integer)("KeyN", 10) '10
      o = Value(Of Integer)("KeyE", 10) '10
      o = Value(Of Integer)("Key1", 10) '99
  
      o = Value(Of Date)("KeyN", #11/11/2010#)
      o = Value(Of Date)("KeyE", #11/11/2010#)
      o = Value(Of Date)("Key2", #11/11/2010#)
  
      o = GetSetting(Of Integer)("KeyN", 10) '10
      o = GetSetting(Of Integer)("KeyE", 10) '10
      o = GetSetting(Of Integer)("Key1", 10) '99
  
      o = GetSetting(Of Date)("KeyN", #11/11/2010#)
      o = GetSetting(Of Date)("KeyE", #11/11/2010#)
      o = GetSetting(Of Date)("Key2", #11/11/2010#)
  
      Stop
  End Sub
  </code></pre>