Answer the question
In order to leave comments, you need to log in
Method chaining of overloaded methods in c#?
Let there be an abstract class AbstractClass and a class that implements it ExtendedClass. An abstract class defines an abstract modify method that returns an object itself to implement method chaining. The type of the returned object is AbstractClass, since we do not know which class will override this abstract class.
abstract class AbstractClass
{
protected int _value;
public AbstractClass setValue(int value)
{
_value = value;
return this;
}
abstract public AbstractClass modify();
public int getValue()
{
return _value;
}
}
class ExtendedClass : AbstractClass
{
public override ExtendedClass modify()
{
_value++;
return this;
}
public override ExtendedClass modifyAgain()
{
_value *= 2;
return this;
}
}
ExtendedClass c = new ExtendedClass();
int value = c.setValue(42).modify().modifyAgain().getValue();
Error 1 "ConsoleApplication1.ExtendedClass.modify()": Return type must be "ConsoleApplication1.AbstractClass" to match overridden member "ConsoleApplication1.AbstractClass.modify()" D:\projects\ConsoleApplication1\ExtendedClass.cs 10 39 ConsoleApplication1
abstract class AbstractClass<T> where T: AbstractClass<T>
{
protected int _value;
public T setValue(int value)
{
_value = value;
return (T) this;
}
abstract public T modify();
public int getValue()
{
return _value;
}
}
class ExtendedClass : AbstractClass<ExtendedClass>
{
public override ExtendedClass modify()
{
_value++;
return this;
}
public override ExtendedClass modifyAgain()
{
_value *= 2;
return this;
}
}
Answer the question
In order to leave comments, you need to log in
First, I don't understand why make ExtendedClass the return type in the implementation of the modify() method. This is not a method override, but a bug.
Do this:
class ExtendedClass : AbstractClass
{
public override AbstractClass modify()
{
_value++;
return this;
}
}
Everything will work as you intended. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question