Search code examples
c#.netclass.net-coretypecasting-operator

C# Interface Type Casting using Base class


Hi I am wondering if it is possible to cast type in Interface and its concrete implementation in below way.

 public class BaseTypeClass

 public class BaseTypeV1 : BaseTypeClass

 public class BaseTypeV2 : BaseTypeClass

 public class BaseTypeV3 : BaseTypeClass



 public interface IProcessBaseType<T> where T : BaseTypeClass

      void Process(T baseType)



 public class ProcessBassTypeClass : IProcessBassType

      void Process(BaseTypeV1 data)

      void Process(BaseTypeV2 data)

      void Process(BaseTypeV3 data)

Solution

  • It is as simple as doing this:

    public class ProcessBassTypeClass : IProcessBaseType<BaseTypeV1>, IProcessBaseType<BaseTypeV2>, IProcessBaseType<BaseTypeV3>
    {
        public void Process(BaseTypeV1 baseType)
        {
            throw new NotImplementedException();
        }
    
        public void Process(BaseTypeV2 baseType)
        {
            throw new NotImplementedException();
        }
    
        public void Process(BaseTypeV3 baseType)
        {
            throw new NotImplementedException();
        }
    }
    

    An alternative that you might want to consider is this:

    public interface IProcessBaseType
    {
        void Process<T>(T baseType) where T : BaseTypeClass;
    }
    
    public class ProcessBassTypeClass : IProcessBaseType
    {
        public void Process<T>(T baseType) where T : BaseTypeClass
        {
            throw new NotImplementedException();
        }
    }
    

    This allows for any object of type BaseTypeClass to be passed and allows Process to call typeof(T) to get the actual type at run-time. Useful if you want to dynamically build the list of processors that you have available.


    Here's a simple example of how you can add type-specific processors at run-time when using the second code example:

    public class ProcessBassTypeClass : IProcessBaseType
    {
        private Dictionary<Type, Delegate> _processors = new Dictionary<Type, Delegate>();
    
        public void AttachProcessor<T>(Action<T> processor) where T : BaseTypeClass
        {
            _processors[typeof(T)] = processor;
        }
    
        public void Process<T>(T baseType) where T : BaseTypeClass
        {
            if (_processors.ContainsKey(typeof(T)))
            {
                ((Action<T>)(_processors[typeof(T)])).Invoke(baseType);
            }
            else
            {
                throw new NotSupportedException();
            }
        }
    }