Interface inheritance and abstract method overriding

Let's say we have a hierarchy of interfaces: IBaseThing<T> and IChildThing:IBase<ChildThing>. Also there are two classes like this:

internal abstract class Base<T>
{
    public abstract IBaseThing<T> Thing {get;}
}

and

internal class Concrete:Base<ChildThing>
{
    public override IChildThing Thing
    {
        get
        {
            return GetChildThing();
        }
     }
}

What will happen is as bellow:

'Concrete' does not implement inherited abstract member 'Base.get'

I want to skip casting (IChildThing)this.Thing all over Concrete class. What I supposed to do?

Answers


You can't do that. The type system is rightly objecting to you attempting to change the method type in the overriding class. IChildThing might derive from IBaseThing, but it is not the same thing. For example, you might add some more methods to IChildThing later on. Then one class (Concrete) would be promising a returned object with a different signature than the base class - that's a type error.

If you need to refer to a IChildThing in some cases, how about something like:

internal class Concrete : Base<ChildThing>
{
    public override IBaseThing<ChildThing> Thing
    {
        get { return ChildThing; }
    }

    public IChildThing ChildThing { get; set; }
}

If all you have is a Base though, then you can't get at the IChildThing safely. That's the nature of a strongly typed system like this. If that's a problem, then if you gave a more concrete example I might be able to suggest how to restructure to avoid that problem.


Try this solution:

public interface IBaseThing {}

public interface IChildThing : IBaseThing {}

internal abstract class Base<T> where T : IBaseThing
{
    public abstract T Thing {get;}
}

internal class Concrete:Base<IChildThing>
{
    public override IChildThing Thing
    {
        get
        {
            return GetChildThing();
        }
     }

     public IChildThing GetChildThing()
     {  
        // Your impelementation here...
        return null;
     }
}

Need Your Help

Java Foreach with a condition

java foreach

Is it possible for Java foreach to have conditions?

What pre-existing services exist for calculating distance between two addresses?

algorithm geolocation distance

I'd like to implement a way to display a list of stored addresses sorted by proximity to a given address.