Is this a good way to expose generic base class methods through an interface?
- by Nate Heinrich
I am trying to provide an interface to an abstract generic base class.  I want to have a method exposed on the interface that consumes the generic type, but whose implementation is ultimately handled by the classes that inherit from my abstract generic base.
However I don't want the subclasses to have to downcast to work with the generic type (as they already know what the type should be).
Here is a simple version of the only way I can see to get it to work at the moment.
public interface IFoo
{
    void Process(Bar_base bar);
}
public abstract class FooBase<T> : IFoo 
    where T : Bar_base
{
    abstract void Process(T bar);
    // Explicit IFoo Implementation
    void IFoo.Process(Bar_base bar)
    {
        if (bar == null) throw new ArgumentNullException();
        // Downcast here in base class (less for subclasses to worry about)
        T downcasted_bar = bar as T;
        if (downcasted_bar == null)
        {
            throw new InvalidOperationException(
                          string.Format("Expected type '{0}', not type '{1}'",
                                        T.ToString(), bar.GetType().ToString());
        }
        //Process downcasted object.
        Process(downcasted_bar);            
    }
}
Then subclasses of FooBase would look like this...
public class Foo_impl1 : FooBase<Bar_impl1>
{
     void override Process(Bar_impl1 bar)
     {
         //No need to downcast here!
     } 
}
Obviously this won't provide me compile time Type Checking, but I think it will get the job done...
Questions:
 1. Will this function as I think it will?
 2. Is this the best way to do this?
 3. What are the issues with doing it this way?
 4. Can you suggest a different approach?
Thanks!