Search⌘ K

Type Casting and Classes

Learn to apply type casting in C# class hierarchies by exploring inheritance, upcasting, downcasting, and using safe casting methods. Understand how to handle casting errors using exception handling or the as keyword to manage type conversions effectively in object-oriented programming.

Introduction

In a previous lesson, we touched upon the topic of type casting and saw some examples where we cast primitive types between one another:

byte age = 24;
int ageAsInt = age; // Implicit cast

In this lesson, we’ll discuss type casting in the context of classes. Consider a set of following classes:

C#
namespace TypeCasting
{
public class Vehicle
{
public string Model { get; internal set; }
public decimal Price { get; internal set; }
public int NumberOfWheels { get; internal set; }
}
}

These three classes can be visualized by the following ...