Monday, March 28, 2011

How do I declare the constructor for a generic class with a non-generic base class with parameters

I have a base class which is non-generic with a derived generic class. The AbstractRepository and ILoggingManager are provided by the IoC framework.

Base Class

public abstract class EventHandlerBase
    : AbstractDataProvider
    , IEventHandler
{
    public EventHandlerBase(
        AbstractRepository data,
        ILoggingManager loggingManager
        )
        : base(data, loggingManager)
    {
    }
}

Derived Class

public abstract class EventHandlerBase<TDetail>
    : EventHandlerBase
    where TDetail : Contracts.DeliveryItemEventDetail
{
}

I would like to declare a constructor in the derived class that will call the non-generic base class, but I do not know the syntax.

From stackoverflow
  • public class EventHandlerBase(AbstractRepository data,
                                  ILoggingManager loggingManager)
         : base(data, loggingManager)
    {
         // Whatever
    }
    

    should work fine. If it doesn't, could you show the problems you're getting?

    EDIT: I think the whole base class thing may be clouding the issue here. When you declare a constructor in a generic type, you don't specify the type parameters. For example, List<T> would look something like:

    public class List<T>
    {
        public List()
        {
        }
    }
    

    The idea is that within the class declaration, T is already known - you only specify type parameters when you want to add more of them, e.g. for a generic method like ConvertAll.

    Antony Scott : so, are you suggesting I remove the generic part from my derived class?
    Jon Skeet : Just in the constructor. The constructor itself isn't generic. I'll add that to my answer.
  • Should it not be more like:

    public abstract class EventHandlerBase<TDetail> : EventHandlerBase    
      where TDetail : Contracts.DeliveryItemEventDetail
    {
      public EventHandlerBase(AbstractRepository data, ILoggingManager loggingManager)
        : base(data, loggingManager)
      {
         // Initialize generic class
      }
    }
    
    Antony Scott : I have tried that, but the compiler gave an error. I've just tried again and it is working now. Thinking about it I didn't rebuild the code per-se, I just let the background compiler kick in. Visual Studio tries to build as your going along. Obviously that doesn't quite work all the time.

0 comments:

Post a Comment