EDIT: In direct relation to
I know that my example is not very expansive, but I am looking to try and understand is how this version of polymorphism works, does it (depending on the code writen within the function) return the correct derived class. Can you give me a simple working example on how it works.
You can write a method anywhere that returns a type like what you have.
Public Function Do() As BaseClass
End Function
This function doesn't have to exist in the derived class at all. All this does is return an object. This would return the object of type BaseClass just like a Function FUBAR() As Int32 would return an integer.
END EDIT
Here's a nice example that I think I saw on MSDN a couple years back.
Every cat in the world is a Cat. It's also an animal. It's also a living thing. But not every cat is the same. Take the following example.
public class Cat
{
public string Genus { get; set; }
public string Species { get; set; }
public void Eat(object something)
{
}
public void Sleep(int hours)
{
}
public void BodilyFunctions()
{
}
}
public class Tiger : Cat
{
public Tiger()
{
Genus = "Panthera";
Species = "tigris";
}
public void GoHunting()
{
Eat("Human");
Sleep(9);
BodilyFunctions();
}
public void BeLazyBecauseItsHotInIndia()
{
Sleep(12);
}
}
public class HouseCat : Cat
{
public HouseCat()
{
Genus = "Felis";
Species = "catus";
}
public void EatFromTheBowl()
{
Eat("CatFood");
}
public void EverydayLife()
{
Purr();
EatFromTheBowl();
Purr();
BeLazy();
Purr();
}
public void BeLazy()
{
Sleep(12);
}
public void Purr()
{
}
}
House cats don't eat people, but both house cats and tigers have a genus and a species. Now technically I should be using an Interface here because both House Cat and Tiger (be-verb-form of is) are Cats, but they also both "have" a genus and species, so this applies.
What does this mean? It means that your base class (which in this case SHOULD be abstract, but that's another course of discussion and study), gets morphed and extended into other things by changing it's initial setup. However, in .NET there is only single inheritance, so you must be mindful that when you inherit a class, you inherit the entirety of that class, and that can change the way you look at code.
An ASP.NET MVC commonality (a real-world example) is to use Controllers for particular sections of a site, say a secured section that requires authentication. You can just as easily put a decorator on each of your controller methods, or you can implement a "BaseController" that all controllers inherit from, and check there. The school of thought you might see out there for something like this is DRY -- don't repeat yourself.