Laurence
Laurence

Reputation: 1020

How to force a class to implement a property that derives from a specific base class/interface (rather than is of a specific type)

In my solution, there are a number of classes C1, C2, C3 etc. that all inherit from a common abstract base class CB.

There are also a number of classes D1, D2, D3 etc. that act as a data-source for the corresponding C class (e.g. the data-source for C1 is a local property of type D1 etc). The D classes all inherit from a common abstract base class DB, but vary in their implementation (both inherited and non-inherited properties & methods are used by the C class).

Now, I want to impose a rule that all C classes (i.e. that derive from CB) must implement a "data-source" property, and the type of this property must be derived from DB.

My initial idea was to do this:

public abstract class CB
{
    protected abstract DB DataSource { get; set; } 

    etc.
}

However, this means that the overridden DataSource property in the C classes can only be of type DB, not a type derived from DB.

How can I impose my rule? Ideally CB and DB would remain abstract base classes (because there are non-abstract properties and methods in each that I wish the C and D classes to inherit), but they could be converted to interfaces if needed. However I think I have exactly the same problem if I do that.

Upvotes: 2

Views: 860

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125610

You're looking for generic class:

public abstract class CB<T> where T : DB
{
    protected abstract T DataSource { get; set; } 

    etc
}

Now, C1 should be defined as:

public class C1 : CB<D1>
{
    protected override D1 DataSource { get; set; }
}

Upvotes: 6

Related Questions