C# DownCast vs UpCast

advertisement
C# DownCast vs UpCast
Polymorphism
• Polymorphism is one of the most powerful
mechanisms of OOP
Class Shape
public class Shape
{
protected int m_xpos;
protected int m_ypos;
public Shape()
{
}
public Shape(int x, int y)
{
m_xpos = x;
m_ypos = y;
}
public virtual void Draw()
{
Console.WriteLine("Drawing a SHAPE at {0},{1}", m_xpos, m_ypos);
}
}
Class Circle
public class Circle : Shape
{
public Circle()
{
}
public Circle(int x, int y) : base(x, y)
{
}
public override void Draw()
{
Console.WriteLine("Drawing a CIRCLE at {0},{1}", m_xpos, m_ypos);
}
}
Client Code: Upcast
• Consider the following statement:
Shape s = new Circle(100, 100);
• Upcast: 1) only cast a class to its base class,
2) only consider the static type of an object
• There are two type conversions:
Which type conversion does upcast belong to?
Downcast
• Downcast: only change the static type of an
object.
• Example:
Shape s = new Circle(100, 100);
s.fillCircle();
Circle c;
c = (Circle)s;
s.fillCircle()
Which type conversion does downcast belong to?
More on Downcast
• Since downcast is not safe, the runtime
system checks whether the runtime type of
an object is a derived class of the cast type
or the cast type itself.
• How to make your program without a
runtime exception
foreach (Shape shape in shapes)
{
shape.Draw();
if (shape is Circle)
((Circle)shape).FillCircle();
if (shape is Square)
((Square)shape).FillSquare();
}
Download