Home > Articles > Programming > C#

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Inheriting from the Base Class

Listing 5 illustrates the definition of my subclass: InvoiceDocument.

Listing 5 A Descendant from AnyOldDocument

public class InvoiceDocument : AnyOldDocument
{
public InvoiceDocument(
    int Id, String name, int docType, int price) :
    base(Id, name, docType, price)
{
Console.WriteLine("Creating an invoice document.");
}

public int getPriceValue() { return AssociatedNumber; }
public void setPriceValue(int number)
{ AssociatedNumber = number; }

public override void StoreDocument()
{
Console.WriteLine(
 "Now storing invoice in content management system");
}

Again, in Listing 5 the semantics from the C++ code are preserved. Notice the invocation of the base class constructor in Listing 6.

Listing 6 Constructor Code

public InvoiceDocument(
  int Id, String name, int docType, int price) : 
  base(Id, name, docType, price)

Explicitly calling a base class constructor like this is a useful way of making sure correct initialization occurs. It also provides a good example of separation of concerns. With separation of concerns, each class in the inheritance tree does only as much as it is good at—other duties are carried out by more specialized subclasses. In other words, the concerns (or responsibilities) are separated out among the various code elements.

Another noteworthy item in Listing 6 is the use of the base class properties. This is seen in the methods getPriceValue() and setPriceValue(). These methods make use of the very concise get/set property mechanism that comes for free with C#. The method getPriceValue() calls the base class code in Listing 7.

Listing 7 Getting and Setting C# Properties

public int AssociatedNumber
{
get { return associatedNumber; }
set { associatedNumber = value; }
}

The method InvoiceDocument.getPriceValue() implicitly calls the base class get code. I really like this mechanism in C# because it enforces a discipline in regard to member data. This is fairly similar to the JavaBeans pattern of enforcing get/set methods in class definitions. The pattern is provided in order to help programmers avoid non-standard representations and also to foster a standard way of writing classes.

  • + Share This
  • 🔖 Save To Your Account