Chapter 3: Learning Just Enough C# and VB.NET: Types and Members

71

Listing 3-4 Code using inheritance

C#:

Cashier cashr = new Cashier(); cashr.FirstName = "May";

VB:

Dim cashr As New Cashier cashr.FirstName = "May"

According to Listing 3-4, Cashier does not have a field named FirstName. However, Employee does have a FirstName field and Cashier derives from Employee. Because of inheritance, Cashier automatically inherits FirstName, and the code in Listing 3-4 is perfectly legal. Inheritance can be thought of as specialization in the sense that, in this example, Cashier is a specialized kind of Employee. To take advantage of this specialization, you could add a new field to your new Cashier class called “assignedCashRegister” where now, not only does the Cashier class have the fields and methods of Employee, it is able to hold the value for a specific cash register name or number. An instance of the Employee class would not be able to contain this information. The .NET Framework uses inheritance extensively to offer you reusable class libraries.

TIP

You can often use the phrase “is a” to describe the relationship between inherited classes when starting from the child class. For example, you can say “Cashier is an Employee.” If you apply this phrase technique to your software design and the sentence sounds logically correct, then you’ve probably used inheritance correctly.

The class Snippet

C# has a class snippet, but VB doesn’t. Before using the class snippet, create a new class file by right-clicking the project, select Add New Item Code File, and name the file Manager. You’ll now have a blank file to work with. To use the class snippet, type cl and press TAB, TAB; and you’ll see the snippet template in Figure 3-1.

Figure 3-1 The C# class snippet template

Page 94
Image 94
Microsoft 9GD00001 manual Class Snippet, Listing 3-4 Code using inheritance