Diego Martelli
Diego Martelli

Reputation: 302

C# Implement Interface and inheritance

I'm trying to implment a property interface with a class inherit the declare one. Maybe the example is more easy to understand.

MyClassA is OK, but MyClassB has a compile error 'Test.MyClassB' does not implement interface member 'Test.IMyInterface.PropA'. Any Idea how I can do this?

/****** EDITED CODE ******/

public class BaseClass
{
    public int PropA { get; set; }
}

public class InheritClass : BaseClass
{
    public int PropB { get; set; }
}

public interface IMyInterface
{
    BaseClass PropClass { get; set; }
}


public class MyClassA : IMyInterface
{

    public BaseClass PropClass { get; set; }
}

public class MyClassB : IMyInterface
{

    public InheritClass PropClass { get; set; }
}

Upvotes: 0

Views: 94

Answers (3)

M.kazem Akhgary
M.kazem Akhgary

Reputation: 19149

this is what you should do

public class BaseClass
{
    public int PropA { get; set; }
}

public class InheritClass : BaseClass
{
    public int PropB { get; set; }
}

public interface IMyInterface
{
    BaseClass PropClass { get; set; }
}


public class MyClassA : IMyInterface
{

    public BaseClass PropClass { get; set; }
}

public class MyClassB : IMyInterface
{
    private BaseClass _propClass;

    public BaseClass PropClass
    {
        get { return (InheritClass)_propClass; }
        set { _propClass = (InheritClass)value; }
    }
}

this is not directly possible, also why you are trying to do this. if you have base class you can use its child to set or get...

Upvotes: 1

Khamill
Khamill

Reputation: 51

You should add PropA in implements of MyClassB:

public class MyClassB : IMyInterface
{
**public int PropA { get; set; }**
public int PropB { get; set; }
}

Upvotes: 0

Enigmativity
Enigmativity

Reputation: 117055

Your interface requires that all classes that implement it have the property int PropA { get; set; }, but your class MyClassB doesn't have this method yet is inheriting IMyInterface.

So you have two options.

One, just implement the interface:

public class MyClassB : IMyInterface
{
    public int PropA { get; set; }
    public int PropB { get; set; }
}

Or, two, if you wish to only expose PropB on MyClassB then you could explicitly implement the interface (and assuming that PropB should be the implementation) then you would do this:

public class MyClassB : IMyInterface
{
    int IMyInterface.PropA { get { return this.PropB; } set { this.PropB = value; } }
    public int PropB { get; set; }
}

Upvotes: 0

Related Questions