views:

39

answers:

1

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...
   }
}
+3  A: 

If T is always going to be derived from FlatFileRecord, then constrain it that way:

public class FlatFile<T> where T : FlatFileRecord
{
   public void Save(T record)
   {
      FlatFileRecord flatRecord = record;
      flatRecord.RecordNumber...
   }
}

If you need to make do without the constraint for some reason, you can cast to object and then back down again:

public class FlatFile<T>
{
   public void Save(T record)
   {
      FlatFileRecord flatRecord = (FlatFileRecord)(object)record;
      flatRecord.RecordNumber...
   }
}
Jon Skeet
I knew there would be a simple way to do it! I should probably use 'where T : FlatFileRecord' to enforce it. I think I need to read some more about generics...
Tim