I've just coded this in C# to try and understand what's happening when you downcast/upcast an instance of a class.
Class1.cs
using System;
public class Shapes
{
protected int _x;
protected int _y;
public Shapes()
{
_x = 0;
_y = 0;
}
public virtual void Printing()
{
Console.WriteLine("In Shapes");
}
}
public class Circle: Shapes
{
public override void Printing()
{
Console.WriteLine("In Circle");
}
}
public class Square : Shapes
{
public new void Printing()
{
Console.WriteLine("In Square");
}
}
------------------------------------------------------------------------------------------
And now to Program.cs
using System;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
Shapes test1 = new Shapes();
Circle test2 = (new Circle());
Square test3 = new Square();
test1.Printing(); //In Shapes
test2.Printing(); //In Circle
test3.Printing(); //In Square
Console.WriteLine("------");
Shapes test4 = test2;
Shapes test5 = test3;
test4.Printing(); //In Circle (?)
test5.Printing(); //In Shapes (Ok)
Console.WriteLine("------");
Circle test6 = (Circle)test4;
Square test7 = (Square)test5;
test6.Printing(); //In Circle
test7.Printing(); //In Square
Console.WriteLine("------");
Square test10 = (Square)test4; //System.InvalidCastException: 'Unable to cast object of type 'Circle' to type 'Square'.'
Console.ReadLine();
}
}
}
So the questions are:
Can someone explain what's happening when I upcast then downcast?
Why does test4 print "In circles" when I've made it into back into a base class?
After test4 has been made into a Shape, why can't it go back down into Square (test10)?
1/3) When you downcast/upcast the object doesn't actually change type, it's just the methods and fields that you have access to that change. That's why you can't go from a
Shape
to aSquare
if theShape
was aCircle
at the start. TheCircle
and theSquare
are bothShapes
yes, but aCircle
is not aSquare
.2) Since the object does not change type when you cast it,
test4
is still aCircle
. It's just that you "don't know it anymore". In fact if you print it's type by callingtest4.GetType()
you would getCircle