Lesson 3: Constructing Classes

johnmora's picture

Now we get to the meat and potatoes of object oriented programming. All programs,except the simplest, require constructing one or more custom classes with multiple properties and methods for performing tasks related to the object. I now discuss how to make custom classes.

What is Inheritance?

With the thousands of classes, methods and properties in the .NET Framework, it would be impossible to keep track of them all were it not for the consistent implementation of them all. As an example every class has a ToString() method that performs exactly the same task (converting an instance of the class into a string).This consistency is possible because of inheritance and interfaces (interfaces will be covered a little later). Use inheritance to create new classes from existing ones. This post will not be the only one referring to inheritance and how it adds functionality to classes. Previously I discussed creating custom exception classes, you can easily create one from inheriting from System.ApplicationException. Below is an example of of a custom exception and its implementation.

   1: class DerivedException : System.ApplicationException{
   2:     public override string Message{
   3:         get { return "An error occurred in the Application,"}
   4:     }
   5: }
   6: //You can throw and catch the new exception since this custom
   7: //class inherits the behavior of the base class, shown below.
   8: try{
   9:     throw new DerivedException();
  10: }
  11: catch (DerivedException ex){
  12:   Console.WriteLine("Source: {0}, Error {1}", ex.Source, ex.Message);
  13: }

The custom exception not only supports the throw/catch behavior, it also includes a Source member (among others) inherited from System.ApplicationException. Another benefit of inheritance is the ability to use derived classes interchangeably. This concept is called polymorphism.  As an example, there are five classes that inherit from the System.Drawing.Brush base class: LinearGradientBrush, PathGradientBrush, SolidBrush, and TextureBrush. The Graphics.DrawRectangle method requires a Brush class object as one of its parameters but you never pass an object of the base Brush class to the Graphics.DrawRectangle. Instead you pass an object of one of the derived classes, the Graphics.DrawRectangle method can accept any of them. Also, if you created a custom class derived from the brush class, you could also pass an object of that class to Graphics.DrawRectangle.

What is an Interface?

Interfaces (aka contracts) define a common set of members that all classes which implement the interface must provide. As an example the IComparable interface defines the CompareTo method, which evaluates two instances of a class to he compared for equality.  All classes which implement the IComparable  interface, whether custom created or built into the .NET Framework, can be compared for equality.

The IDisposable interface provides a single method, Dispose, to enable assemblies that create an instance of your class to free up any resources the instances have consumed. The following is an example of a class which implements the IDisposable interface. Note: the following was created using Microsoft Visual Studio 2008.

Create a class declaration (class NewClass) and add the interface declaration ( : IDisposable). When using Visual Studio, right click the interface declaration and then click implement interface.

image

You would write code in the Dispose method to de-allocate any resources you had allocated (replacing the “throw new NotImplementedException()”).

   1: class NewClass : IDisposable{
   2:     #region IDisposable Members
   3:     public void Dispose(){
   4:         throw new NotImplementedException();
   5:     }
   6:     #endregion
   7: }

Here is a list of the most commonly used interfaces in the .NET Framework:

Interface Description
IComparable Implemented by types whose values can be ordered like numeric and string classes. IComparable is required for sorting.
IDisposable Defines methods for disposing of an object manually. This interface is important for large objects that consume considerable resources, or objects such as databases that lock access to resources.
IConvertable Enables a class to be converted to a base type such as Boolean, Byte, Double or String.
IClonable Supports copying an object.
IEquatable Allows you to compare instances of a class for equality. When implemented you can do if (a==b).
IFormattable Enables you to convert the value of an object into a specially formatted string which provides greater flexibility than the base ToString method.

You can also create your own interfaces also which would be useful if you need to create multiple custom classes that behave similarly and can be used interchangeably. The following code defines an interface containing three members.

   1: interface IMessage{
   2:     bool Send();
   3:     string Message { get; set; }
   4:     string Address { get; set; }
   5: }
   6: //Implement this interface in a new class.
   7: class EmailMessage : IMessage{
   8:     public bool Send(){
   9:         throw new Exception("The operation is not implemented.");
  10:     }
  11:     public string Message{
  12:         get{
  13:             throw new Exception("The operation is not implemented.");
  14:         }
  15:         set{
  16:             throw new Exception("The operation is not implemented.");
  17:         }
  18:     }
  19:     public string Address{
  20:         get{
  21:             throw new Exception("The operation is not implemented.");
  22:         }
  23:         set{
  24:             throw new Exception("The operation is not implemented.");
  25:         }
  26:     }
  27: }

Visual Studio allows for creating an interface from a custom class and has a shortcut for specifically doing so. To do so you would right click the class while in Visual Studio, Click Refactor and then click Extract Interface. Specify the interfaces name, select the public members that form the interface and click OK.

Classes can implement multiple interfaces. You could create a class which implements both the IComparable and IDisposable.

What are Partial Classes?

Partial classes allow you to split a class definition across multiple source files. The benefit is that it hides details of the class definition so that developers can focus on more significant portions.  The Windows Form class is an example of a partial class. Prior to 2005 Visual Studio’s form classes included code generated by the form designer, Now that code is hidden in a partial class stored in files named form.Designer.cs.

Lesson 3 to be continued…

Powered by Drupal - Design by artinet