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?
You can use generics:
interface IObject<T> where T : IObject<T>
{
T GetSomeObject();
}
public class ObjectClass : IObject<ObjectClass> { ... }
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With