Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Inherit method but with different return type?

Tags:

c#

inheritance

Given the following classes:

ClassA
{
     public ClassA DoSomethingAndReturnNewObject()
     {}    
}

ClassB : ClassA
{}

ClassC : ClassA
{}

Is there a way to get ClassB and ClassC to inherit the method but customize the return type to their own class?

I prefer not to copy the method from ClassA and change the type there.

I need to get a ClassB object when I call ClassB.DoSomethingAndReturnNewObject().

I need to get a ClassC object when I call ClassC.DoSomethingAndReturnNewObject().

Something like calling a constructor based on current type like: this.GetType()? But I have no clue how to actually do that.

like image 400
Peterdk Avatar asked Nov 12 '09 16:11

Peterdk


2 Answers

You need to create a protected virtual method for the DoSomethingAndReturnNewObject to use:

class ClassA
{
    protected virtual ClassA Create()
    {
        return new ClassA()
    }

    public ClassA DoSomethingAndReturnNewObject()
    {
        ClassA result = Create();
        // Do stuff to result
        return result;
    }
}

class ClassB : ClassA
{
     protected override ClassA Create() { return new ClassB(); }
}

class ClassC : ClassA
{
     protected override ClassA Create() { return new ClassC(); }
}

Note the return type remains ClassA but the object instance type will be the specific class.

like image 160
AnthonyWJones Avatar answered Sep 27 '22 23:09

AnthonyWJones


What you're describing is a covariant return type and is not supported in C#.

However, you could create ClassA as an open generic and have the closed generic inheritors return their own type.

Example:

public abstract class ClassA<T> where T: ClassA<T>, new()
{
    public abstract T DoSomethingAndReturnNewObject();
}

public class ClassB: ClassA<ClassB>
{
    public override ClassB DoSomethingAndReturnNewObject()
    {
        //do whatever
    }
}
like image 29
Joseph Avatar answered Sep 28 '22 00:09

Joseph