How do I pull functionality from a base class that returns the base type, into an inherited class?
I have a base class Chapter
, and a child class EnhancedChapter
that adds some functionality to Chapter
.
Unfortunately, one base class method returns the class type. I can access this method in the child class, but it since it returns the base type, and not the child type, I'm having trouble bringing its functionality into the child class.
Here's the base class (Page
is implemented elsewhere, you'll get the picture):
class Chapter
{
public List<Page> pages;
public Chapter()
{
pages = new List<Page>();
}
public Chapter CalculatedChapter(DateTime date)
{
pages.ForEach(p => p.CalculatedPage(date));
return this;
}
}
Here's the child class:
class EnhancedChapter : Chapter
{
public int? PageCount()
{
if (pages != null) return pages.Count; else return null;
}
}
Now, when I want to use CalculatedChapter()
in a the child class, I run into issues:
EnhancedChapter enhancedChapter;
// won't work, returns Chapter not EnhancedChapter
enhancedChapter = new EnhancedChapter().CalculatedChapter(DateTime.Now);
Some options I thought of, but that didn't fit well with me: I could do a cast here, but that seems prone to errors down the road. I also thought about somehow feeding the result of CalculatedChapter()
into the child class constructor, but can't figure out how to do that.