M
M
mayhem2012-12-29 15:19:45
C++ / C#
mayhem, 2012-12-29 15:19:45

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;
    }
}

Let's implement the abstract modify method:
class ExtendedClass : AbstractClass
{
    public override ExtendedClass modify()
    {
         _value++;
        return this;
    }

    public override ExtendedClass modifyAgain()
    {
         _value *= 2;
        return this;
    }
}

Let's try to run the code:
ExtendedClass c = new ExtendedClass();
int value = c.setValue(42).modify().modifyAgain().getValue();

We get:
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

I understand why this happens, but I don't understand how to do method chaining in C#. Is there a way to say "this class" when specifying a return type in a method?
PS: Solution:
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

1 answer(s)
D
Dzuba, 2012-12-29
@Dzuba

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.
Secondly, I will answer your question. There is a way to specify the return type in a method. This can be done using generics: generic methods or generic types. But in this case, there is no need for this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question