'Force a Subclass to Define Extra Fields in C#

My company has a base database model class that is subclassed by particular instances of our product. The class represents primary keys in a database. The base class has a field, which we'll call AlwaysPresent, which is common to all instances of the product and is not used in querying.

abstract class BaseClass
{
    private string AlwaysPresent
}

But it is a requirement that subclasses add at least one more field, as we will use reflection later to treat those other fields as database column names for a query. If there are no other fields, we can't query.

So, my question: is it possible to use C#'s reflection capabilities to force a non-abstract subclass to define new fields without specifying their names?

I am a Python programmer by trade, and I know exactly how to solve this kind of problem in Python using metaclasses. To my knowledge, C# does not have metaclasses. And I cannot raise an exception in the base class constructor, because (for various reasons) we don't use constructors for these classes (just initializers), and even if we did the base class constructor could be overridden.



Solution 1:[1]

Reflection cannot be used to force something. At least not at compile time. Via reflection you can read how a type is. In your case you can probably check its fields and throw an exception if required at run time.

In any case usually it is much better to use properties instead of fields. Properties are more extensible and better to hide the internal structure of a class.

A common way to enforce a specific design (properties or methods definition) of a class is to use interfaces.You can have also a class that implement more than one interface.

If properties names or fields are not know when designing the interface you cannot enforce your requirements at compile time but only at run time.

Another common c# technique is to decorate properties or fields with attributes. Maybe you can create a custom attribute and at run time check for fields with that attribute (always with reflection).

Solution 2:[2]

This can be done with aspects, specifically PostSharp. It allows you to execute custom code during compilation (in fact, it hooks on postcompile action) in the CompileTimeValidate:

http://www.postsharp.net/blog/post/Architectural-Validation

You can of course replace PostSharp with any custom code triggered on postcompile at build-time.

Solution 3:[3]

Turns out this is not a feature in C#, but you can write it like this to force people to implement it

abstract class BaseClass
{
    private abstract string GetAlwaysPresent();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Caveman