Dunno
Dunno

Reputation: 3684

Set generic type property in derived classes

I have a generic type G<T> where T : A, where A is an abstract class. In each class B derived from A I want to have a field of type G<B>, without writing repetetive code, however I'm not sure if it's even possible. One way to do this would be

abstract class A
{
    protected object g;

    protected abstract void SetG();

    public A()
    {
        SetG();
    }
}

class B : A
{
    protected override void SetG()
    {
        this.g = new G<B>();
    }

    public B() : base() {}
}

But this would mean a lot of repetetive code in every derived class. Is there a better way to do this?

Upvotes: 3

Views: 236

Answers (2)

wablab
wablab

Reputation: 1733

You could add an extra abstract class in between:

public abstract class A<T> : A where T : A
{
    protected override void SetG()
    {
        this.g = new G<T>();
    }
}

...then, update your B declaration to:

public class B : A<B>
{
    public B() : base() { }
}

Upvotes: 7

Robert Columbia
Robert Columbia

Reputation: 6418

I believe that what you are trying to do is a Covariant Conversion. See this MSDN article on using delegates and see if that works for you. Look in the section "Using Delegates with Covariant Type Parameters".

In your A:, create a delegate:

Func<G<A>> GetG;

Then, in your derived classes, set this func pointer to a function of type

Func<G<B>>

Bingo!

Upvotes: 0

Related Questions