Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can method inheritated from interface return another type that in interface?

Lets say I have a code like this:

interface IObject
{
     IObject GetSomeObject();
}

public class ObjectClass : IObject
{
     IObject GetSomeObject()
     {
     // method implementation here
     }
}

Is there any way, that I make GetSomeObject() method of class ObjectClass make return ObjectClass, no IObject?

I know I can use it like this:

ObjectClass object1= someObject1.GetSomeObject() as ObjectClass;

But what I want to achieve is:

public class ObjectClass : IObject
{
     ObjectClass GetSomeObject()
     {
     // method implementation here
     }
}     

Is it possible in that way?

like image 616
Rico Avatar asked Feb 27 '26 04:02

Rico


2 Answers

You can use generics:

interface IObject<T> where T : IObject<T>
{
    T GetSomeObject();
}

public class ObjectClass : IObject<ObjectClass> { ... }
like image 122
Lee Avatar answered Mar 01 '26 06:03

Lee


You can use an explicit interface implementation:

public interface IObject
{
     IObject GetSomeObject();
}

public class ObjectClass : IObject
{
    public ObjectClass GetSomeObject()
    {
        return this;
    }

    IObject IObject.GetSomeObject()
    {
        return this;
    }
}

This way, comsumers that access ObjectClass can call ObjectClass GetSomeObject(), whereas consumers that access an instance of this class through IObject can only call IObject GetSomeObject().

like image 23
sloth Avatar answered Mar 01 '26 06:03

sloth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!