Reputation: 58745
I have a base class that has an abstract method which returns a list of itself.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public abstract class baseclass
{
public abstract List<baseclass> somemethod();
}
}
And a descendant that tries to override the base class's method by returning a list of *it*self.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class childclass : baseclass
{
public override List<childclass> somemethod()
{
List<childclass> result = new List<childclass>();
result.Add(new childclass("test"));
return result;
}
public childclass(string desc)
{
Description = desc;
}
public string Description;
}
}
But I get this error:
Error 1 'ConsoleApplication1.childclass.somemethod()':
return type must be 'System.Collections.Generic.List<ConsoleApplication1.baseclass>'
to match overridden member 'ConsoleApplication1.baseclass.somemethod()'
C:\Users\josephst\AppData\Local\Temporary Projects\ConsoleApplication1childclass.cs
0 42 ConsoleApplication1
What's the best approach to have a base class return a list of itself, overriding the base class's method that does the same thing?
Upvotes: 2
Views: 180
Reputation: 4778
Generic i s nice solution, but don't use public abstract List<baseclass> somemethod();
it's bad practice
You should use non-virtual interface pattern
public abstract class BaseClass<T>
{
protected abstract List<T> DoSomeMethod();
public List<T> SomeMethod()
{
return DoSomeMethod();
}
}
public class ChildClass : BaseClass<ChildClass>
{
protected override List<ChildClass> DoSomeMethod(){ ... }
}
Upvotes: 2
Reputation: 460228
The error message is self-explanatory. To override the method you need to return a List<baseclass>
.
public override List<baseclass> somemethod()
{
List<childclass> result = new List<childclass>();
result.Add(new childclass("test"));
return result;
}
Upvotes: 1
Reputation: 7088
When overriding a method, a signature of overriding method must exactly match the signature of the method being overriden. You can achieve what you want with generics:
public abstract class BaseClass<T>
{
public abstract List<T> SomeMethod();
}
public class ChildClass : BaseClass<ChildClass>
{
public override List<ChildClass> SomeMethod() { ... }
}
Upvotes: 2