- Upcasting: conversion from a derived class to a base class
- All objects can be implicitly converted to a base class reference.
Shape shape = circle; // Shape is base class and circle is derived class
Downcasting: conversion from a base class to a derived class Downcasting requires a cast. Circle circle= circle; // Shape is base class and circle is derived class
Casting can throw an exception if the conversion is not successful. We can use the as keyword to prevent this. If conversion is not successful, null is returned. Circle circle = shape as Circle;
if (circle != null)
We can also use the is keywordif (shape is Circle) {
var circle = (Circle) shape;
}
No comments:
Post a Comment