My question here is, what are the negative effects of using a generic function such as this? Calling this function does work, and in a test console module, it compiles perfectly fine. I do know this is not a strongly typed function, and is %100 bad practice. But it works... perfectly. The purpose of a function like this, would be to handle string input that needs to be inserted in a particular format depending on the type. I also read some other questions on this here on stackoverflow, and suggestions pointed to using (Of T) functions, and variations like that. Why not do it this way? or is there another simple way of accomplishing this without creating a whole nothing class or larger amounts of code. I know this isn't the "elegant" way of handling this either, so if anyone has suggestions, I'm all ears. Thank you! :)
Private Function ConvertFieldValueByType(ByVal type As Field_Type, ByVal value As String)
If type = Field_Type.FIELD_TYPE_DATE Then
Dim dt As Date = DirectCast(TypeDescriptor.GetConverter(New Date(1990, 5, 6)).ConvertFrom(value), Date)
Return dt
ElseIf type = Field_Type.FIELD_TYPE_DATETIME Then
Dim dt As DateTime = DirectCast(TypeDescriptor.GetConverter(New DateTime(1990, 5, 6)).ConvertFrom(value), DateTime)
Return dt
ElseIf type = Field_Type.FIELD_TYPE_BLOB Then
Return value
ElseIf type = Field_Type.FIELD_TYPE_LIST Then
Return value
ElseIf type = Field_Type.FIELD_TYPE_LONG Then
Return Convert.ToInt64(value)
ElseIf type = Field_Type.FIELD_TYPE_NUMBER Then
Return Convert.ToInt32(value)
ElseIf type = Field_Type.FIELD_TYPE_SHORT Then
Return Convert.ToInt16(value)
ElseIf type = Field_Type.FIELD_TYPE_STRING Then
Return value
ElseIf type = Field_Type.FIELD_TYPE_TIME Then
Dim dt As DateTime = DirectCast(TypeDescriptor.GetConverter(New DateTime(1990, 5, 6)).ConvertFrom(value), DateTime)
Return dt
ElseIf type = Field_Type.FIELD_TYPE_UNKNOWN Then
Return value
Else
Return value
End If
End Function
Yes, sometimes things like that become necessary, especially if the final type is not known at compile time (making most other solutions awkward). My main feedback/observation would be:
Field_Type
looks to be an enum, so you could make this tidier and more efficient with aSwitch
. Re naming, I would probably call that something related to...Parse...
since it takes aString
(perhaps with a matching...Format...
that does the reverse), and I think some of the returns (especially "blob" and "list") look a bit dubious. But otherwise: it gets the job done.Minor point: your
GetConverter
code can take a type rather than having to init a struct each time; in C# terms,typeof(DateTime)
etc.