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

Using two audio queues in iPhone application

iphone ios4 iphone-sdk-3.0

In my application I am using two audio queues for play and two audio queues for recording. At a time only one record queue and one play queue is active. What I do is, first of all I start first rec...

After calling Assembly.LoadFrom(file), file is not being released when app closes

.net plugins reflection dll compilation

I use Assembly.LoadFrom to load custom dll's, but one of these dll's is maintained in my project solution and is offered with the application.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.