Type Casting and Classes
Explore how to use type casting within class hierarchies in C#. Understand upcasting and downcasting between base and derived classes, and learn safe casting techniques with the as and is operators to handle type compatibility and avoid exceptions.
We'll cover the following...
We previously introduced type casting and demonstrated examples of casting between primitive types:
byte age = 24;int ageAsInt = age; // Implicit cast
In this lesson, we will discuss type casting in the context of classes. We start by defining the base Vehicle class, which contains the shared properties for all vehicle types.
Lines 6–8: We define properties common to all vehicles (
Model,Price,NumberOfWheels).
Next, we define a Car class that inherits from the Vehicle class.
Line 1: We declare a file-scoped namespace
TypeCasting.Line 3: We define
Caras a derived class ofVehicle.Line 5: We add a property specific to
Car.Lines 7–10: We set the inherited ...