Microsoft KB Archive/307205

= How to use inheritance in Visual C# =

Article ID: 307205

Article Last Modified on 12/11/2006

-

APPLIES TO


 * Microsoft Visual C# 2005
 * Microsoft Visual C# .NET 2002 Standard Edition

-



This article was previously published under Q307205





For a Microsoft Visual Basic .NET version of this article, see 307222.

IN THIS TASK
SUMMARY
 * Requirements
 * Create a New Console Application
 * Create an Abstract Base Class
 * Write Code for the Base Class
 * Create a Derived Class
 * Write Code for the Derived Class
 * Verify It Works



SUMMARY
This step-by-step article shows you how to use inheritance in Visual C#.

Inheritance is an important object-oriented concept. It allows you to build a hierarchy of related classes, and to reuse functionality defined in existing classes.

In the following examples, you will define a base class that contains fields and methods for a generic bank account. You will then define a derived class that represents a particular kind of bank account. The derived class will inherit members from the base class, override selected members, and add new members for the new kind of account.

back to the top

Requirements
Prior knowledge required:
 * C# syntax
 * Object-oriented concepts

back to the top

Create a New Console Application

 * 1) Start Visual Studio. NET or Microsoft Visual Studio 2005 and create a new C# console application project named UseInheritance.
 * 2) Save the project.

back to the top

Create an Abstract Base Class
 In Solution Explorer, switch to the Class View (If you can not see it, click Class View in the View menu). Right-click the UseInheritance project, point to Add, and then click Add Class.

Note In Visual C# 2005. point to Add, and then click Class.  In the C# Add Class Wizard, type Account. Click the Abstract radio button, and then click Finish.

The Account class is displayed. Notice the class definition includes the abstract modifier keyword: public abstract class Account {

} 

back to the top

Write Code for the Base Class
  In the Code View window, add two fields to the Account class to represent the account balance and the name of the account holder: private string name;       // Only accessible in base class protected double balance;  // Accessible in base class and derived class   Modify the constructor as follows to initialize these fields: public Account(string nm, double bal) {  this.name = nm; this.balance = bal;

}   Add the following methods to the class. The virtual keyword means these methods can be overridden in derived classes: public virtual void Credit(double amount) {  this.balance += amount; }

public virtual void Debit(double amount) {  this.balance -= amount; }

public virtual void Display {  Console.WriteLine(&quot;Name={0}, balance={1}&quot;, this.name, this.balance);

} </li>  Add the following method to the class. Because this method is not marked as virtual, it cannot be overridden in derived classes. This method provides the capability to change the name of the account holder. public void ChangeName(string newName) {  this.name = newName;

} </li>  Add the following method to the class. The abstract keyword means this method must be overridden in derived classes: public abstract double CalculateBankCharge; </li></ol>

back to the top

Create a Derived Class
 In the Class View, right-click the UseInheritance project. On the Shortcut menu, choose Add and then click Add Class.</li> In the C# Add Class Wizard, type SavingsAccount, and then click Finish.</li> View the code for the SavingsAccount class.</li>  Change the SavingsAccount class definition as follows, so that SavingsAccount inherits from Account: public class SavingsAccount : Account {

} </li></ol>

back to the top

Write Code for the Derived Class
  Add a field to the SavingsAccount class: private double minBalance;  // If the balance drops below minBalance, // the bank will charge a fee on the account </li>  Modify the SavingsAccount constructor to initialize the fields in the base class and in this class: public SavingsAccount(string nm, double bal, double min) : base(nm, bal)          // Call base-class constructor first {  minBalance = min;         // Then initialize fields in this class

} </li>  Add the following methods to the SavingsAccount class. These methods override the virtual methods inherited from the base class: public override void Debit(double amount) {  if (amount <= balance)    // Use balance, inherited from base class base.Debit(amount);   // Call Debit, inherited from base class } public override void Display {  base.Display;          // Call Display, inherited from base class Console.WriteLine(&quot;$5 charge if balance goes below ${0}&quot;, minBalance);

} </li>  You must override all abstract methods from the base class. Add the following method to the SavingsAccount class: public override double CalculateBankCharge {  if (balance < minBalance) return 5.00; else return 0.00;

} </li></ol>

back to the top

Verify It Works
 Display the code for Class1.cs in the Code View window.</li>  In the Main method, create a SavingsAccount object and display it as follows: SavingsAccount sa = new SavingsAccount(&quot;Freda Smith&quot;, 100.00, 25); sa.Display; </li>  Add the following code to call public methods in SavingsAccount or Account: sa.Credit(100); sa.Debit(180); sa.ChangeName(&quot;Freda Jones&quot;); sa.Display; Console.WriteLine(&quot;Bank charge: ${0}&quot;, sa.CalculateBankCharge); </li> <li>Build the application.</li> <li> Set a breakpoint at the start of the Main method, and start the application in the debugger. Step into each statement, and observe which methods are called during the application. The application displays the following information on the console: Name=Freda Smith, balance=100 $5 charge if balance goes below $25 Name=Freda Jones, balance=20 $5 charge if balance goes below $25 Bank charge: $5 </li></ol>

back to the top

Keywords: kbhowtomaster KB307205

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.