Search code examples
c#inheritanceattributesradixderived

C#. Can I automatically substitute derived class instead of base class


Language is C#.
Say i have overridden method in class A

    class A:B
    {
        protected override void Method(BaseClass bc)
        {
            (DerivedClass)bc.DerivedClassField = blabla;
        }
    }

Is there any library/language feature/etc using which i can write following:

    class A:B
    {
        protected override void Method(BaseClass bc)
        {
            bc.DerivedClassField = blabla;
        }
    }

by, for instance, adding some attribute to class A or something?
Sorry for crappy formatting.


Solution

  • You could use generics to do this in a type-safe way:

    class A<T> where T : BaseClass {
        protected virtual void Method(T bc) { ... }
    }
    
    class B : A<DerivedClass> {
        protected override void Method(DerivedClass bc) {
            bc.DerivedClassField = blabla;
        }
    }
    

    but this might cause other problems if you even want to use A<T> without knowing T, in which case I would use the cast (if the class structure means the cast won't fail) or redefine your object model.