Home > Articles > Software Development & Management > Object Technology

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Object-Oriented Features

As an object-oriented language, C# supports inheritance, encapsulation, and polymorphism. Conceptually, the capabilities of C# are the same as other object-oriented languages, but the syntax and semantics differ in subtle ways that developers must be aware of. A discussion of basic object-oriented concepts is outside the scope of this book, but the following sections detail the primary ways C# supports the object-oriented principles of inheritance, encapsulation, and polymorphism.

Inheritance

Inheritance in a C# class is specified in the class declaration. A C# class may inherit from only a single base class. However, a class may inherit multiple interfaces, as will be explained in the next chapter in the section on interfaces. Listing 3.5 shows how to declare an inheritance relationship between classes.

Listing 3.5 Declaring Inheritance (Inheritance.cs)

using System;

public class BaseClass
{
  public double myDouble = 9.3d;
}

public class DerivedClass : BaseClass
{
}

class Inheritance
{
  static void Main()
  {
   DerivedClass myDerived = new DerivedClass();

   Console.WriteLine("myDerived.myDouble = {0}", 
     myDerived.myDouble);
   Console.ReadLine();
  }
}

Listing 3.5 demonstrates how a derived class inherits from its base class. Although myDouble doesn't physically reside in DerivedClass, it is still a member of DerivedClass by virtue of inheritance. This is why myDouble can be accessed through an instance of DerivedClass in the Main method.

Hiding

A derived type can hide members of its base type, making the base type member invisible without an explicit reference to the base type member. Hidden members must be decorated with the new modifier; otherwise, the C# compiler will issue a warning.

Warnings for the new modifier are by design, and there are a couple of good reasons for this. Because part of the C# philosophy is for the code to be explicit in what it does, warnings on the new modifier make the developers think twice about what they are doing.

Viewing Compiler Messages

To see compiler warnings, choose Tools, Options and check Show Command Line in the Compiling and Running group box. Press Shift+F9 to build the program, and the Messages window will appear at the bottom of the screen with a Build tab that will display warnings, if any. Click the pin glyph on the right of the window to get it to slide down and out of the way while you're working.

More importantly, the new modifier prevents versioning problems that occur when a third-party component is updated. If that third-party component introduces a member with the same identifier as a local derived type, the condition will be caught by the compiler warning. Code written in other languages with implicit polymorphism would break under these conditions. C# support of polymorphism is described in the section "Polymorphism." Listing 3.6 shows how to hide base type members.

Listing 3.6 Hiding Base Type Members (Hiding.cs)

using System;

public class BaseClass
{
  public double myDouble = 9.3d;
}

public class DerivedClass : BaseClass
{
  public new double myDouble = 5.7d;
}

class Hiding
{
  static void Main()
  {
   DerivedClass myDerived = new DerivedClass();

   Console.WriteLine("myDerived.myDouble = {0}", 
     myDerived.myDouble);
   Console.ReadLine();
  }
}

By physically declaring myDouble, DerivedClass hides access to myDouble in BaseClass. Therefore, referencing myDouble through an instance of DerivedClass will return a result of the myDouble in DerivedClass only. This behavior applies to other type members also, such as methods, making code more robust by avoiding implicit polymorphism.

Abstract Classes

Abstract classes provide both implementation and interface to derived classes. Because they are abstract, they cannot be instantiated. The primary difference between abstract classes and interfaces is that abstract classes may define implementation, whereas interfaces may not. Listing 3.7 shows how to define and use an abstract class.

Listing 3.7 Defining and Using an Abstract Class (AbstractClass.cs)

using System;

public abstract class BaseClass
{
  public abstract void AbstractMethod();

  public virtual void ImplementedMethod()
  {
   Console.WriteLine("Implemented Method.");
  }
}

public class DerivedClass : BaseClass
{
  public override void AbstractMethod()
  {
   Console.WriteLine("Abstract Method.");
  }
}

class AbstractClass
{
  static void Main()
 {
    DerivedClass myDerived = new DerivedClass();

   myDerived.ImplementedMethod();
   myDerived.AbstractMethod();

   Console.ReadLine();
  }
}

Abstract methods, as shown in BaseClass of Listing 3.7, are decorated with the abstract modifier and don't have an implementation. The C# compiler forces derived classes to implement all abstract members of an abstract class. The DerivedClass implements the abstract method, AbstractMethod, by specifying the override modifier.

Notice the virtual modifier on the ImplementedMethod method. This means that derived classes can override this method with their own implementation. An abstract class method doesn't need the virtual modifier, but its usefulness could be limited without it.

Encapsulation

C# classes have members, such as indexers, methods, and properties, that help encapsulate the internal state of a type. Visibility of type members is controlled with a set of modifiers, shown in Table 3.1. These modifiers control the interface of a type to external types.

Table 3.1 Visibility Modifiers

Visibility Modifier

Who Can See

public

All other types

protected

Derived types

internal

Types within the same assembly

protected internal

Types within the same assembly and derived

private

Within the same type only


Listing 3.8 and Listing 3.9 show how to use the visibility modifiers to control the public interface of a class.

Listing 3.8 Calling Class for Visibility Modifier Demo (Visibility.cs)

using System;

internal class ExternalDerived : PublicClass
{
  internal void ExternalDerivedMethod()
  {
   Console.WriteLine("External Derived Method");
   ProtectedMethod();
  }
}

class Visibility
{
  static void Main()
  {
   PublicClass myPublicClass = new PublicClass();
   myPublicClass.PublicMethod();

   ExternalDerived myExternalDerived = new ExternalDerived();
   myExternalDerived.ExternalDerivedMethod();

   Console.ReadLine();
  }
}

Listing 3.9 Called Class for Visibility Modifier Demo (CalledLibrary.cs)

using System;

internal class BaseInternal
{
  public void BaseInternalMethod()
  {
   Console.WriteLine("Internal Method.");
  }

  protected internal void ProtectedInternalMethod()
  {
   Console.WriteLine("Protected Internal Method.");
  }
}

internal class DerivedInternal : BaseInternal
{
  internal void DerivedInternalMethod()
  {
   ProtectedInternalMethod();
  }
}

public class PublicClass
{
  public void PublicMethod()
  {
   Console.WriteLine("Public Method.");

   BaseInternal myBaseInternal = new BaseInternal();
   myBaseInternal.BaseInternalMethod();

   DerivedInternal myDerivedInternal = new DerivedInternal();
   myDerivedInternal.DerivedInternalMethod();
  }

  protected void ProtectedMethod()
  {
   Console.WriteLine("Protected Method.");
   PrivateMethod();
  }

  private void PrivateMethod()
  {
   Console.WriteLine("Private Method.");
  }
}

Here is the output of running this program, demonstrating the sequence in which the methods execute:

Public Method.
Internal Method.
Protected Internal Method.
External Derived Method
Protected Method.
Private Method.

This is going to be a little complex, so look at each modifier in Listings 3.8 and 3.9 before following the explanation. Be sure to make Listings 3.8 and 3.9 separate projects. Listing 3.8 will be a console application and Listing 3.9 will be a class library. Creating a console application is explained in Chapter 1, which is something that has to be done for each of the other programs in Chapters 2 through 4.

To create an assembly for Listing 3.9, right-click on the project group and select Add New Project (see Figure 3.1). When the New Items dialog appears, select the C# Projects folder (see Figure 3.2) and then select the Class Library project type. Double-clicking the Class Library icon or clicking the OK button will bring up the New Project dialog. Give the project a name and directory and click the Create button.

Figure 3.1Figure 3.1 Adding a project from the Project Manager.

Figure 3.2Figure 3.2 Creating a class library project from the New Items dialog.

For a program to use a class library, it must reference it in the Project Manager. Expand the folder of the application for Listing 3.8 to reveal the References folder. Right-click on the References folder and select Add Reference. When the Add Reference dialog appears (see Figure 3.3), select the Project References tab, which exposes a list of all the projects in the current project group. Select the project for Listing 3.9 and click the Add Reference button. When the project name appears in the New References list, click the OK button. This places a reference from the console application project for Listing 3.8 to the class library project for Listing 3.9 in the References folder list (see Figure 3.4). In this example I named the console application project for Listing 3.8 as Visibility and the class library project for Listing 3.9 as CalledLibrary. To run the program, make sure that Listing 3.8 is the active project by double-clicking its project name, or right-click and select Activate from the context menu.

Figure 3.3Figure 3.3 The Add Reference dialog.

Figure 3.4Figure 3.4 Reference to a Class Library project.

When the CalledLibrary project reference is first added to the Visibility project reference list, the following error message will appear in the Build tab of the Messages window:

"[References Error] Could not find the assembly "CalledLibrary" on the 
Assembly Reference Search Path, or in the Global Assembly Cache." 

If your Messages window is not open, choose Tools, Options and make sure the Show Command Line box is checked on the Environment Options page of the Options dialog. There will also be a small red x on the icon for the CalledLibrary reference in the Visibility project's References folder. The message and error icon indicate that the CalledLibrary has not been compiled yet. To compile both projects and eliminate these errors, select the Visibility project title and select Build from the context menu. Running the project by pressing F9 or selecting Run, Run Without Debugging will also get rid of the errors. C#Builder will automatically detect whether projects and their references need to be compiled and will compile those items that need it prior to execution.

First, let's trace the code from the Main method of Listing 3.8. The first method call is to PublicMethod in Listing 3.9, which is declared public. PublicMethod is the only method of PublicClass that can be called because the other two methods are inaccessible to the Visibility class. PrivateMethod may only be accessed by members within PublicClass, and Visibility cannot get to ProtectedMethod because it does not inherit from PublicClass.

The only way to get to the code in the assembly for Listing 3.9 is through the public and protected methods of PublicClass, which is public. The other classes, DerivedInternal and BaseInternal, are declared internal, which means that only code within the same assembly may access them. Additionally, the ProtectedInternal method of the BaseInternal class is only accessible via the DerivedInternal class because its modifier only allows derived types within the same assembly to access it.

The PublicMethod method of PublicClass can access the BaseInternalMethod method of BaseInternal because it is within the same assembly. The same access applies to the DerivedInternalMethod method of DerivedInternal because it is also in the same assembly. The modifiers of BaseInternalMethod and DerivedInternalMethod demonstrate that types in an assembly may access public and internal members, respectively, of internal types within the same assembly. Finally, the ProtectedMethod of PublicClass has access to PrivateMethod because both are members of the same type.

The next call in the Main method of the Visibility class is to the ExternalDerived class, which is declared internal itself. I named it ExternalDerived because of its relationship to PublicClass. It is not internal to code in Listing 3.9 and derives from PublicClass. Remember that Listing 3.9 is a separate assembly. Because ExternalDerived is derived from PublicClass, it can call ProtectedMethod.

Polymorphism

Polymorphism—the ability of multiple types to be treated the same way—is implemented in C# with the virtual and override modifiers. The first declaration of an indexer, method, or property in a base class intended to support polymorphism will be decorated with the virtual modifier. Derived types wanting to implement polymorphism would decorate applicable members with the override modifier. Listing 3.10 demonstrates how to set up and implement polymorphism.

Listing 3.10 Implementing Polymorphism (Polymorphism.cs)

using System;

public class BaseClass
{
  public virtual void RunMe()
  {
   Console.WriteLine("BaseClass.");
  }
}

public class DerivedClass1 : BaseClass
{
  public override void RunMe()
  {
   Console.WriteLine("DerivedClass1.");
  }
}

public class DerivedClass2 : BaseClass
{
  public override void RunMe()
  {
   Console.WriteLine("DerivedClass2.");
  }
}

class Polymorphism
{
  static void Main()
  {
   BaseClass[] polyTypes =
   {
     new BaseClass(),
     new DerivedClass1(),
     new DerivedClass2()
   };

   foreach (BaseClass polyType in polyTypes)
   {
     polyType.RunMe();
   }

   Console.ReadLine();
  }
}

In Listing 3.10, DerivedClass1 and DerivedClass2 inherit BaseClass. Because BaseClass declares RunMe as virtual, both derived classes can override RunMe, which they do by using the override keyword and redefining their own versions of RunMe.

The power of this capability is demonstrated in the Main method, where polyTypes is declared as an array of type BaseClass and initialized with three objects. Because the array type is BaseClass, derived types can also be added. Because of the inheritance relationship, they are both their own specific type and BaseClass types.

The foreach loop iterates through the polyTypes array calling each object's RunMe method. Because their derived types override RunMe, polymorphism allows their methods to be invoked through a base class reference at runtime.

  • + Share This
  • 🔖 Save To Your Account