Kevin
Kevin

Reputation: 2631

Calling generic method with generic collection

I'm am just getting started with generics, and am confused by how to implement the following scenario.

This is my base class:

 public abstract class UnclaimedProperty
 {
     public abstract string Key { get; }
     public virtual void Process() { }
     public virtual void Process(string FileName) { }

     abstract public void WriteReport<T>(List<T> PropertyRecords, string FileName);
 }

In my implementations I would like to pass a concrete list to the override. something like:

public class PennUnclaimed : UnclaimedProperty
{
   public override void Process(string FileName)
   {
      var reportDollarRecords = new List<PennUnclaimed>();
      //add items here
      WriteReport(reportDollarRecords, "PennCash");
   }

   public override void WriteReport(List<UnclaimedProperty> PropertyRecords, string FileName)
   {
      //write report here
   }

}

I get error:

'PennUnclaimed' does not implement inherited abstract member
 'UnclaimedProperty.WriteReport<T>(List<T>, string)'

What would be the correct way to implement this?

Upvotes: 2

Views: 48

Answers (1)

Nkosi
Nkosi

Reputation: 247561

Based on your comments, consider making the abstract class generic.

public abstract class UnclaimedProperty<T> where T : UnclaimedProperty<T> {
    public abstract string Key { get; }
    public virtual void Process() { }
    public virtual void Process(string FileName) { }

    abstract public void WriteReport(List<T> PropertyRecords, string FileName);
}

That way the implementation would look like this

public class PennUnclaimed : UnclaimedProperty<PennUnclaimed> {
    public override void Process(string FileName) {
        var reportDollarRecords = new List<PennUnclaimed>();
        //add items here
        WriteReport(reportDollarRecords, "PennCash");
    }

    public override void WriteReport(List<PennUnclaimed> PropertyRecords, string FileName) {
        //write report here
    }

    public override string Key {
        get {
            return string.Empty; //TODO:return key 
        }
    }
}

The constraint on the abstract class for the generic argument will allow it to be the type of the current class being implemented.

Upvotes: 2

Related Questions