bakester14
bakester14

Reputation: 163

How do I declare an array of any type (derived from a given type) in an abstract class?

I'm not sure what the correct English words are for my problem, so I think it's best to illustrate it in code. I have a basic, abstract Windows Forms class that I use to create many derived Windows Forms that serve similar purposes. In the abstract base class, which we'll call Alfred, I have an array of type Buddy. Sometimes though, when I want to inherit Alfred, I also want to override class Buddy with some functionality specific to the new derived form, AlfredJunior.

So, in the definition of class Alfred:

protected Array<Buddy> importantArray;

And what I want in AlfredJunior is this:

private class BuddyJunior : Buddy
{
    public int newField;
    // Constructors omitted
}
protected Array<BuddyJunior> importantArray;

I'd like for the methods defined in Alfred to access and use the elements of importantArray just as if they were of type Buddy, instead of BuddyJunior. But I need just a touch of extra functionality (one extra field) in BuddyJunior in the inherited form AlfredJunior. What is the correct way to go about this?

Upvotes: 3

Views: 3551

Answers (1)

Enigmativity
Enigmativity

Reputation: 117057

This is what you need:

public abstract class Alfred<B> where B : Buddy
{
    protected B[] importantArray;
}

public class Buddy { }

public class BuddyJunior : Buddy
{
    public int newField;
}

public class Alfred : Alfred<Buddy> { }

public class AlfredJunior : Alfred<BuddyJunior> { }

Upvotes: 7

Related Questions