Casting objects: upcast : Object Cast « Class Interface « C# / C Sharp






Casting objects: upcast

Casting objects: upcast
 

using System;
   
public class CPU {
  public string model;
   
  public CPU(string model) {
    this.model = model;
  }
   
  public void Start() {
    Console.WriteLine(model + " started");
  }
}
   
public class Intel : CPU {
  public bool convertible;
   
  public Intel(string model, bool convertible) : base(model) {
    this.convertible = convertible;
  }
}
   
public class AMD : CPU {
  public bool sidecar;
   
  public AMD(string model, bool sidecar) : base(model) {
    this.sidecar = sidecar;
  }
   
  public void PullWheelie() {
    Console.WriteLine(model + " pulling a wheelie!");
  }
   
}
   
   
class Test {
  public static void Main() {
    Intel myIntel = new Intel("MR2", true);
   
    // cast myIntel to CPU (upcast)
    CPU myCPU = (CPU) myIntel;
   
    Console.WriteLine("myCPU.model = " + myCPU.model);
    myCPU.Start();
  }
}
           
         
  








Related examples in the same category

1.Casting Objects
2.Downcast will fail.
3.This code raises an exception at run time because of an invalid cast
4.Casting objects: downcastCasting objects: downcast
5.Variables of type object can accept values of any data type