RSS

Upcasting x Downcasting

27 Apr

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;
}
Advertisements
 
1 Comment

Posted by on April 27, 2015 in General

 

Tags: , , ,

One response to “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

 
%d bloggers like this: