C# Object Casting and Reference Conversions

In this chapter you will learn:

  1. What is Object Casting and Reference Conversions
  2. Upcasting
  3. Downcasting

Description

An object reference can be:

  • Implicitly upcast to a base class reference
  • Explicitly downcast to a subclass reference

An upcast always succeeds; a downcast succeeds only if the object is suitably typed.

Upcasting

An upcast operation creates a base class reference from a subclass reference. For example:


public class Shape { 
    public string Name; 
} //from   ww w  .j  a va 2  s  .  c  o m

public class Circle : Shape   // inherits from Shape 
{ 
  public long Radius; 
} 

public class Rectangle : Shape   // inherits from Shape 
{ 
  public decimal Width; 
} 

Rectangle msft = new Rectangle();
Shape a = msft;              // Upcast

Downcasting

A downcast operation creates a subclass reference from a base class reference. For example:


public class Shape { 
    public string Name; 
} /*from   w w  w.  ja  va  2  s.  com*/

public class Circle : Shape   // inherits from Shape 
{ 
  public long Radius; 
} 

public class Rectangle : Shape   // inherits from Shape 
{ 
  public decimal Width; 
} 



Rectangle msft = new Rectangle();
Shape a = msft;                      // Upcast
Rectangle s = (Rectangle)a;                  // Downcast
Console.WriteLine (s.Width);   // <No error>
Console.WriteLine (s == a);          // True
Console.WriteLine (s == msft);       // True

Next chapter...

What you will learn in the next chapter:

  1. What are Delegates
  2. Syntax to create delegate
  3. Example for creating a delegate
  4. Writing Plug-in Methods with Delegates
  5. Instance Versus Static Method Targets
  6. Casting delegate variables
  7. How to use delegate array
  8. Return delegate from a method
  9. Use delegate as the function parameter
Home »
  C# Tutorial »
    C# Types »
      C# Object
C# Object
C# new operator
C# this Reference
C# Null
C# Nullable Types
C# ToString Method
C# Object Initializers
C# GetHashCode
C# Object Casting and Reference Conversions