Search code examples
c#genericsinheritanceabstraction

How can I decrease verbosity when inheriting from C# generic types to non-generic types?


With C# generics (specifically, type parameters for classes), is it possible to refer to specified type parameter values in an specialized ("non-generic") type (class) that extends/inherits the generic one? In this case, I'm overriding virtual methods of the generic (inherited) type in the inheriting (specialized) one; I suspect that's important to the question/answer, but don't want to limit the case if not.

I might just be looking for what C calls a typedef; the closest thing I can think of in C# is a using alias (using Type = Some.Longer.Namespaced.Type;). Here is an example w/ the using alias, but even this is still very verbose and is no fun to update when e.g. the name of ConcreteType changes (or some other refactor, where the boundaries/encapsulations of logic shift, not the logic itself):

using ConcreteType = Some.Longer.Namespaced.Type;

public class ConcreteTypeLogic : CrudLogic<ConcreteType>
{
    // default ctor for `ConcreteTypeLogic`
    public ConcreteTypeLogic()
    { /* ... */ }
    // other ctor for `ConcreteTypeLogic`
    /* ... */
    // dtor for `ConcreteTypeLogic`
    public ~ConcreteTypeLogic()
    { /* ... */ }

    // "Create" implementation for `ConcreteType`
    public override ConcreteType Create(ConcreteType value)
    { /* ... */ }

    // "Read" implementation for `ConcreteType`
    public override ConcreteType Read(ConcreteTypeIdentifier valueId)
    { /* ... */ }

    /* ... */
}

It seems like a C-style typedef or a CPP-style macro is really what I want though, because ConcreteTypeLogic and the constructor/destructor will need to update as well, as well as any other relevant aspects where the type (class) name is part of the binding/contract.


Solution

  • Outside of the using alias, the language (C#) doesn't support this naming indirection.

    It's not common to use a pre-processor when building C# (.NET) projects, and the common alternative is to use development tools to expedite this "work." Considering that the definition of a type doesn't need to reside in a single source file, or even a single assembly, development tooling seems the best approach to managing this.

    Thanks to the commenters for their responses.