overburn overburn - 2 months ago 7
C# Question

Child classes inheriting different implementations of the same interface

Okay, I have a small hiccup.

I want to implement an interface with a generic parameter type, and then extend that implementation with another parameter type, and not have to do the initialization all over again.

Basically, I have a similar structure to this:

interface IBase<MemberType>;

abstract class Base : IBase<OneMemberType> {

protected OneMemberType member;
public void init() {
member = new OneMemberType();
}
}


class Extended: Base, IBase<AnotherMemberType> {

}


I want class Extended to have a "member" property of the "AnotherMemberType" type.

AnotherMemberType and OneMemberType both implement the same interface.

Any ideas how i could do that, without explicitly defining it in the Extended class?

This is the actual interface.

interface ILayer<TextureProviderType>
{
Texture2D getTexture();
byte[,] getArray();

void generate();
}


Updated

I'm trying to have specific objects that extend the BaseLayer class and that each use a specific TextureProvider child, and only have to instantiate the texture providers in the base class.

Update 2
Okay, it has nothing to do with interfaces apparently. What I want to have is a generic base class member, that can be assigned a type in the extended children classes.

Rob Rob
Answer

You can implement the interface methods just once and it will work for both interfaces.

If you want different implementations per interface, you must use explicit implementations or use the generic type parameter in the signature of your interface methods.

Point is, you can't have 2 methods with the same signature in your class and have the CLR know which one to use.


Edit: after reading you comment on the problem you're trying to solve:

Wouldn't a generic type parameter in your BaseLayer + inheritance in your TextureProviders work? Would look something like this:

class TextureProvider
{
    public TextureProvider()
    {

    }

    public void Foo()
    {

    }
}

class SpecialTextureProvider : TextureProvider
{
    public SpecialTextureProvider()
        : base()
    {

    }
}

class BaseLayer<TP> where TP : TextureProvider, new()
{
    public BaseLayer()
    {
        var tp = new TP();
    }
}

class SpecificLayer : BaseLayer<SpecialTextureProvider>
{
}

Alternatively, you could use the factory pattern.