Upcasting x Downcasting

Upcasting

Is when you cast an object to its base class type.

public class Person
{ }

public class President : Person
{ }

void Main()
{
    var president = new President();

    // Upcasting
    var person = (Person)president;
}

Downcasting

Well, it’s the opposite of upcasting, when you cast a reference of a base class to one of its derived classes.

You can only downcast when the object’s type is original a derived class, so it’s important to perform some checking prior, such as using as or is operators.

public class Person
{ }

public class President : Person
{ }

void Main()
{
    var president = new President();
    var person = (Person)president;

    // Downcasting
    var president = (President)person;
}

1 thought on “Upcasting x Downcasting”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s