Nathan Schulte Nathan Schulte - 11 months ago 45
C# Question

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

With C# generics (specifically, type parameters for

es), is it possible to refer to specified type parameter values in an specialized ("non-generic") type (
) that extends/inherits the generic one? In this case, I'm overriding
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
; the closest thing I can think of in C# is a
alias (
using Type = Some.Longer.Namespaced.Type;
). Here is an example w/ the
alias, but even this is still very verbose and is no fun to update when e.g. the name of
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
or a CPP-style macro is really what I want though, because
and the constructor/destructor will need to update as well, as well as any other relevant aspects where the type (
) name is part of the binding/contract.

Answer Source

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.