I’m trying to understand inheritance within an MVC application and I have a couple of things I would like clear up if someone can please help.
Question 1
If I have the following three classes which inherit off each other as follows
Public class StandardPage
Public class ArticlePage : StandardPage
Public class NewsPage : ArticlePage
Is the StandardPage class the only BASE class here or is the ArticlePage class also referred to as a BASE class because the NewsPage class derives from it?
In a nut shell are classes that derive from other classes also referred to as BASE classes (for the class that inherits it)?
Question 2
If I have the above classes defined when working in the strongly typed view file (with Razor), if I write the following code
@foreach (var article in Model.Articles)
{
if (article is StandardPage)
{
var articlePage = article as StandardPage;
If the object inside the article var is of type StandardPage, ArticlePage or news page then the articlePage var will be populated without any issues because StandardPage is the BASE class which ArticlePage & NewsPage both inherit from, however if I change the code to the following
@foreach (var article in Model.Articles)
{
if (article is StandardPage)
{
var articlePage = article as ArticlePage;
When the object inside the article var is of type StandardPage I will receive an ‘Object reference not set to an instance of an object’ when trying to populate the articlePage var because StandardPage does not inherit from an ArticlePage (it’s the other way around) and therefore I can’t cast something of type StandardPage into and ArticlePage.
Fingers crossed im nearly there with understanding this but if im way off the mark could someone please point me in the right direction
Thanks in advance