C# Object Casting and Reference Conversions
In this chapter you will learn:
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:
- What are Delegates
- Syntax to create delegate
- Example for creating a delegate
- Writing Plug-in Methods with Delegates
- Instance Versus Static Method Targets
- Casting delegate variables
- How to use delegate array
- Return delegate from a method
- Use delegate as the function parameter
C# Object
C# new operator
C# this Reference
C# Null
C# Nullable Types
C# ToString Method
C# Object Initializers
C# GetHashCode
C# new operator
C# this Reference
C# Null
C# Nullable Types
C# ToString Method
C# Object Initializers
C# GetHashCode