I have to do an export from DB to CSV. (.NET 2)
field; fileld; field... etc
Have 3 types of fields: Alpha, Numeric and Bool respresented as "alphaValue",intValue and True/False.
I try to encapsulate this in a fields collection, in order to export if alpha then set “”, if Bool=>True/False if numeric let as is.
and try to build a CsvField class:
Public Structure?Class CsvField(Of T As ???)
End Structure
Enum FieldType
Alpha
Bool
Numeric
End Enum
possibile usage:
myCollection.Add(new CsvField(DateTime.Now, FileType.Alpha))
myCollection.Add(new CsvField(myInt, FileType.Numeric))
any suggestions welcomed.
No generics needed. Simply use inheritance:
The code example assumes that
valuestores 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
FieldTypeenumeration completely and allIf/Select Caseconstructs that decide on what to do depending on the field type. If you still need to do that, you could replace:with
However, you should generally be able to move such logic into the derived classes and get rid of the
Ifstatements by overriding methods. This is the whole point of the above example.P.S.: In case you’re wondering how you create your
CsvFieldobjects without checking explicitly on the type. One way is to use factory methods and method overloading:For example,
CsvField.Create(False)would create aBoolCsvField“disguised” as aCsvField, so that you can put it inside yourList(Of CsvField)or whatever collection you have.