Home > Articles > Programming > C#

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

Like this article? We recommend

The Base Class

Listing 2 illustrates the original C++ base class called AnyOldDocument.

Listing 2 The C++ Base Class (AnyOldDocument.h)

AnyOldDocument::AnyOldDocument() :
 documentId(0), documentName("No name yet"), documentType(0)
{
printf("Invoking 0-parameter constructor for AnyOldDocument\n");
}

AnyOldDocument::AnyOldDocument(int Id, char* name, int docType) :
 documentId(Id), documentName(name), documentType(docType)
{
printf("Invoking 3-parameter constructor for AnyOldDocument\n");
}

AnyOldDocument::AnyOldDocument(int Id, char* name, int docType, int theNumber) :
 documentId(Id), documentName(name), 
  documentType(docType), associatedNumber(theNumber)
{
printf("Invoking 4-parameter constructor for AnyOldDocument\n");
}

AnyOldDocument::~AnyOldDocument()
{
printf("Invoking the destructor for AnyOldDocument\n");
}

The C++ class in Listing 2 consists of three constructors and a destructor. Let's now convert Listing 2 into C#, as illustrated in Listing 3.

Listing 3 The Base Class Converted from C++ into C#

public abstract class AnyOldDocument
{
private int documentId;
private String documentName;
private int documentType;
private int associatedNumber;

public AnyOldDocument()
{ Console.WriteLine(
"Invoking 0-parameter constructor for AnyOldDocument");
}

public AnyOldDocument(int Id, String name, int docType)
{ Console.WriteLine(
"Invoking 3-parameter constructor for AnyOldDocument");
}

public AnyOldDocument(int Id, String name, int docType, int theNumber)
{ Console.WriteLine(
"Invoking 4-parameter constructor for AnyOldDocument");
documentId = Id;
documentName = name;
documentType = docType;
associatedNumber = theNumber;
}
 
public abstract void StoreDocument();
// Abbreviated code follows
public int DocumentId...
public String DocumentName...
public int DocumentType...    
public int AssociatedNumber...
}

It really is pretty straightforward converting the C++ code into C#. Note a few rules/guidelines:

  1. Make the base class abstract.
  2. Retain the C++ constructors converted into C# syntax.
  3. Get rid of the C++ destructors.

It was probably Item 3 above that had me scratching my head for a while. C# is referred to as a managed language, which means that when objects go out of scope they then become candidates for garbage collection. So, you don't need to worry about object destruction above and beyond letting your objects go out of scope. This is a fairly substantial simplification! In the earlier Informit article, I recommended making destructors virtual in order to ensure they are called by subclasses. In C# land, you don't really need to worry about this.

  • + Share This
  • 🔖 Save To Your Account