Search⌘ K
AI Features

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 previously introduced type casting and demonstrated examples of casting between primitive types:

byte age = 24;
int ageAsInt = age; // Implicit cast
Implicit casting of a byte to an int

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.

C# 14.0
namespace TypeCasting;
public class Vehicle
{
public string Model { get; protected set; }
public decimal Price { get; protected set; }
public int NumberOfWheels { get; protected set; }
}
  • 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.

C# 14.0
namespace TypeCasting;
public class Car : Vehicle
{
public int NumberOfSeatbelts { get; set; }
public Car()
{
NumberOfWheels = 4;
}
}
  • Line 1: We declare a file-scoped namespace TypeCasting.

  • Line 3: We define Car as a derived class of Vehicle.

  • Line 5: We add a property specific to Car.

  • Lines 7–10: We set the inherited ...