Inheritance

A class can inherit from another class to extend or customize the original class. Inheriting from a class lets you reuse the functionality in that class instead of building it from scratch. A class can inherit from only a single class, but can itself be inherited by many classes, thus forming a class hierarchy. In this example, we start by defining a class called Asset:

	public class Asset
	{
	  public string Name;
	}

Next, we define classes called Stock and House, which will inherit from Asset. Stock and House get everything an Asset has, plus any additional members that they define:

	public class Stock : Asset   // inherits from Asset
	{
	  public long SharesOwned;
	}

	public class House : Asset   // inherits from Asset
	{
	  public decimal Mortgage;
	}

Here’s how we can use these classes:

	Stock msft = new Stock { Name="MSFT",
	                         SharesOwned=1000 };

	Console.WriteLine (msft.Name);         // MSFT
	Console.WriteLine (msft.SharesOwned);  // 1000

	House mansion = new House { Name="Mansion",
	                            Mortgage=250000 };

	Console.WriteLine (mansion.Name);      // Mansion
	Console.WriteLine (mansion.Mortgage);  // 250000

The subclasses Stock and House inherit the Name property from the base class Asset.

Note

A subclass is also called a derived class. A base class is also called a superclass.

Polymorphism

References are polymorphic, which means a reference to a base class can refer to an instance of a subclass. For instance, consider the following method:

 public static void Display (Asset asset) { System.Console.WriteLine (asset.Name); ...

Get C# 3.0 Pocket Reference, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.