I’ve made a generic class that saves and queries objects from a flat file. I keep having to change the method arguments to objects so I can cast them and I’m wondering if I’m going about this the right way…
‘T’ will always inherit ‘FlatFileRecord’
This does not compile:
public class FlatFile<T>
{
public void Save(T record)
{
FlatFileRecord castedRecord = (FlatFileRecord)record;
castedRecord.RecordNumber...
}
}
This compiles but seems to defeat the whole point of a strongly typed generic class:
public class FlatFile<T>
{
public void Save(object record)
{
FlatFileRecord castedRecord = (FlatFileRecord)record;
castedRecord.RecordNumber...
}
}
If T is always going to be derived from FlatFileRecord, then constrain it that way:
If you need to make do without the constraint for some reason, you can cast to object and then back down again: