No generics needed. Simply use inheritance:
' abstract base class; you could possibly declare it as an interface instead: '
MustInherit Class CsvField
Public MustOverride Function Export() As String
End Class
' specialized class for alpha-numeric fields: '
Class AlphaCsvField : Inherits CsvField
...
Public Overrides Function Export() As String
Return String.Format("""{0}""", value)
End Function
Private value As String
End Class
' specialized class for bool fields '
Class BoolCsvField : Inherits CsvField
...
Public Overrides Function Export() As String
If value = True Then
Return "True"
Else
Return "False"
End If
End Function
Private value As Boolean
End Class
...
The code example assumes that value
stores the actual value of a field. I hope this example is sufficiently clear. Make your fields collection one for type base class type, e.g. List(Of CsvField)
. It can then contain objects of all derived types, too.
Btw., note how, when using polymorphism, you might be able to get rid of the FieldType
enumeration completely and all If
/ Select Case
constructs that decide on what to do depending on the field type. If you still need to do that, you could replace:
If someCsvField.FieldType = Alpha Then ...
with
If TypeOf someCsvField Is AlphaCsvField Then ...
However, you should generally be able to move such logic into the derived classes and get rid of the If
statements by overriding methods. This is the whole point of the above example.
P.S.: In case you're wondering how you create your CsvField
objects without checking explicitly on the type. One way is to use factory methods and method overloading:
MustInherit Class CsvField
Public Shared Function Create(value As String) As CsvField
Return New AlphaCsvField(value)
End
Public Shared Function Create(value As Boolean) As CsvField
Return New BoolCsvField(value)
End
...
' as in the above code example '
Public MustOverride Function Export() As String
End Class
For example, CsvField.Create(False)
would create a BoolCsvField
"disguised" as a CsvField
, so that you can put it inside your List(Of CsvField)
or whatever collection you have.