R
Random
I want to define a generics method so the user can determine what type they
expect returned from the method. By examining the generics argument, I
would determine the operation that needs to be performed and do just that.
However, out of the two possible ways of doing this, neither seems to work.
I thought I could either...
1) overload the method just based on the generics argument
Public Function GetData (Of T As SqlDataReader) (ByRef command as
SqlCommand) As T
...
End Function
Public Function GetData (Of T As DataSet) (ByRef command as SqlCommand) As T
...
End Function
....or...
2) determine the type without overloading and make sure to return the wanted
type
Public Function GetData (Of T) (ByRef command as SqlCommand) As T
Select Case True
Case TypeOf(T) Is GetType(SqlDataReader)
Return command.ExecuteReader()
Case TypeOf(T) Is GetType(DataSet)
.....(other code)
oDataAdapter.Fill(oDataSet)
Return oDataSet
End Select
End Function
But, #1 doesn't work because changing the generics type won't overload the
function, and #2 doesn't work because I get errors along the lines of "Value
of type '...' cannot be converted to 'T'"
I understand #1 not working, but as long as I'm playing it safe with the
type conversions, why can't I get #2 to work?
expect returned from the method. By examining the generics argument, I
would determine the operation that needs to be performed and do just that.
However, out of the two possible ways of doing this, neither seems to work.
I thought I could either...
1) overload the method just based on the generics argument
Public Function GetData (Of T As SqlDataReader) (ByRef command as
SqlCommand) As T
...
End Function
Public Function GetData (Of T As DataSet) (ByRef command as SqlCommand) As T
...
End Function
....or...
2) determine the type without overloading and make sure to return the wanted
type
Public Function GetData (Of T) (ByRef command as SqlCommand) As T
Select Case True
Case TypeOf(T) Is GetType(SqlDataReader)
Return command.ExecuteReader()
Case TypeOf(T) Is GetType(DataSet)
.....(other code)
oDataAdapter.Fill(oDataSet)
Return oDataSet
End Select
End Function
But, #1 doesn't work because changing the generics type won't overload the
function, and #2 doesn't work because I get errors along the lines of "Value
of type '...' cannot be converted to 'T'"
I understand #1 not working, but as long as I'm playing it safe with the
type conversions, why can't I get #2 to work?