I came across polymorphism in the book that I'm reading and decided to do a little experiment. Essentially what I did was to create a base class called Asset
and two subclasses that derive from Asset, called Property
and Stock
. I created instances of these two types and passed them to this function:
public static void PrintAsset(Asset theAsset)
{
Console.WriteLine(theAsset.name);
Console.WriteLine(theAsset.GetType().ToString());
string x;
if (theAsset.GetType() == typeof(Stock))
{
Stock theStock = (Stock)theAsset;
x = (theStock.numShares * theStock.stockPrice).ToString();
}
else
{
Property theStock = (Property)theAsset;
x = (theStock.value).ToString();
}
Console.WriteLine(x + "\n");
}
Initially, the method only consisted of the first two lines, and the output shocked me since I would've figured the incoming reference (theAsset) would've been cast to Asset
, but .GetType().ToString()
surprisingly produced "...Stock" and "...Property" in the Console output.
I'm assuming the fact that they allow you to see the true class of the object being passed to the method for a reason, so doing something like this should be considered acceptable, but I was wondering if perhaps you SO/SE folks might disagree. Is there some unforeseen problem that this causes?