Presentation is loading. Please wait.

Presentation is loading. Please wait.

C# DownCast vs UpCast.

Similar presentations


Presentation on theme: "C# DownCast vs UpCast."— Presentation transcript:

1 C# DownCast vs UpCast

2 Polymorphism Polymorphism is one of the most powerful mechanisms of OOP

3 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);

4 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);

5 Client Code: Upcast Consider the following statement:
Upcast: 1) only cast a class to its base class, 2) only consider the static type of an object There are two type conversions: Shape s = new Circle(100, 100); Which type conversion does upcast belong to?

6 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?

7 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 ppt "C# DownCast vs UpCast."

Similar presentations


Ads by Google