C# Object Casting and Reference Conversions

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 w w  w  . j av a 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

Downcasting

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


public class Shape { 
    public string Name; 
} //  w ww  .  j a v  a 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
Rectangle s = (Rectangle)a;                  // Downcast
Console.WriteLine (s.Width);   // <No error>
Console.WriteLine (s == a);          // True
Console.WriteLine (s == msft);       // True





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor