O'Reilly logo

C# Essentials by Peter Drayton, Ben Albahari, Brad Merrill

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Inheritance

A C# class can inherit from another class to extend or customize that class. A class can only inherit from a single class but can be inherited by many classes, thus forming a class hierarchy. At the root of any class hierarchy is the object class, which all objects implicitly inherit from. Inheriting from a class requires specifying the class to inherit from in the class declaration, using the C++ colon notation:

class Location { // Implicitly inherits from object
  string name;

  // The constructor that initializes Location
  public Location(string name) {
    this.name = name;
  }
  public string Name {get {return name;}}
  public void Display( ) {
    Console.WriteLine(Name);
  }
}
class URL : Location { // Inherit from Location
  public void Navigate( ) {
    Console.WriteLine("Navigating to "+Name);
  }
  // The constructor for URL, which calls Location's constructor
  public URL(string name) : base(name) {}
}

URL has all the members of Location, and a new member, Navigate:

class Test {
  static void Main( ) {
    URL u = new URL("http://microsoft.com");
    u.Display( );
    u.Navigate( );
  }
}

Tip

The specialized class and general class are referred to as either the derived class and base class or the subclass and superclass .

Class Conversions

A class D may be implicitly upcast to the class B it derives from, and a class B may be explicitly downcast to a class D that derives from it. For instance:

URL u = new URL( );
Location l = u; // upcast
u = (URL)l; // downcast

If the downcast fails, an InvalidCastException ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required