Robert Koritnik
Robert Koritnik

Reputation: 105029

Type inference and inheritance

I have a base class that has some functionality that uses type inference...

public abstract class Processor<T>
{
    ...
    public IProcessBuilder<T, TResult> Process<TResult>(Expression<Func<T, TResult>> propertyOfT)
    {
    }

    public abstract void SetProcessors();
}

Then I have two classes:

public class EntityBase
{
    public string Name { get; set; }
}

public class EntityChild : EntityBase
{
    public string Description { get; set; }
}

And over these two I also have two processors that configure these two classes:

public class EntityBaseProcessor : Processor<EntityBase>
{
    public override void SetProcessors()
    {
        base.SetProcessors();
        this.Process(entity => entity.Name)
            .DoSomething();
    }
}

Now the problem is that I would like to reuse configured process of base entity class for the child class as well to avoid code duplication:

public class EntityChildProcessor: EntityBaseProcessor
{
    public override void SetProcessors()
    {
        base.SetProcessor();
        this.Process(entity => /* entity.Description is of course missing */)
            .DoSomething();
    }
}

Question

I'm apparently tired because I can't seem to find a feasible way to reuse processor classes because inherited processor class should also use the inherited entity class for processing.

I can of course repeat the code and write my other processor as:

public class EntityChildProcessor: Processor<EntityChild>
{
    public override void SetProcessors()
    {
        base.SetProcessor();
        // repeated code for inherited property
        this.Process(entity => entity.Name)
            .DoSomething();
        this.Process(entity => entity.Description)
            .DoSomething();
    }
}

Upvotes: 4

Views: 258

Answers (2)

ie.
ie.

Reputation: 6101

How would it be reasonable to you to declare EntityBaseProcessor as a generic class? Something like this:

public class EntityBaseProcessor<TEntityBase> : Processor<TEntityBase>
    where TEntityBase : EntityBase
{
    public override void SetProcessors()
    {
        base.SetProcessors();
        this.Process(entity => entity.Name)
            .DoSomething();
    }
}

public class EntityChildProcessor : EntityBaseProcessor<EntityChild>
{
    public override void SetProcessors()
    {
        base.SetProcessors();
        this.Process(entity => entity.Description)
            .DoSomething();
    }
}

Upvotes: 0

Tim S.
Tim S.

Reputation: 56536

Make EntityBaseProcessor generic as well:

public class EntityBaseProcessor<T> : Processor<T> where T : EntityBase

public class EntityChildProcessor<T> : EntityBaseProcessor<T> where T : EntityChild

Or: (you can trade the simplicity of a non-generic EntityChildProcessor for the downside of permanently setting T's type)

public sealed class EntityChildProcessor : EntityBaseProcessor<EntityChild>

Upvotes: 1

Related Questions