Deborah's Developer MindScape

         Tips and Techniques for Web and .NET developers.

August 31, 2009

What is a Class?

Filed under: C#,OOP,VB.NET @ 5:48 pm

Humans like to classify things, to find similarities in things, and to group
them accordingly. Things with similar attributes (properties) and behaviors
(methods) are grouped. In object-oriented terminology, the definition of
the properties and methods that describe a particular classification is called
a class. A class defines a particular object type. You can think of a class as a
blueprint, providing the details of how objects of that type are made.

[To begin with an overview of OO, start here.]

A cookie cutter is another analogy often used to illustrate the relationship
between objects and a class. The cookie cutter is the class and
provides the definition; it specifies the size and shape. The cookies are the
objects created from the cookie cutter class.

For example, an employee class can have name, address, and occupation
properties. Sam Smith and Jessica Jones are both objects from the
employee class. Likewise, a time sheet class can have employee, date, and hours properties and a calculate pay method. Each person’s weekly time
sheet is then an object from the time sheet class.

A specific object created from a class is called an instance of the
class. Each instance can have values for the defined set of properties and
can perform the defined methods. So Sam is an instance of the employee
class, and Jessica’s time sheet for last week is an instance of the time sheet

The set of properties and methods described by a class are often called
class members. A class defines the members, including the actual code to
maintain the property values and perform the methods. Each object that
is an instance of that class can execute the methods and retain values for
each property.

A class itself normally does not maintain state, meaning that it normally
does not have any property values. Nor does it normally execute the class
methods. Instead, the class defines the properties and contains the implementation of the methods that are used by each object created from the
class. Each object has values for the properties and performs the methods.
You do not eat the cookie cutter or fill out a time sheet class. You eat each
cookie and fill out each individual time sheet.

The .NET Framework itself is composed of a set of classes. For
example, the button in the Visual Studio Toolbox represents a Button
class. Each time you add a button to a form, you create an instance of
that Button class. The Button class has specific defined methods, such
as Focus, and properties, such as Name and Text. The Button class
itself does not have a value for the Name or Text properties. Nor can it
have focus. Instead, it contains the implementation of the Name and Text
properties and the Focus method. The Button objects that you create as
instances of that Button class have values for the Name and Text properties
and perform the Focus method.

Code you write normally resides in a class. If you type some
code in a form, your code is in the form’s class. Even if you write code in a
Visual Basic module, the code compiles as a class!

If you have never created a class, the following example may help you
visualize the code for a TimeSheet class.

In C#:

public class TimeSheet
    public Employee CurrentEmployee { get; set; }
    public decimal TotalHours { get; set; }

    private DateTime _WeekEndingDate;
    public DateTime WeekEndingDate
    { get
        { return _WeekEndingDate; }
            if (value > DateTime.Now.Date)
                throw new Exception(
                    "Date must be on or before today’s date");
            _WeekEndingDate = value;

    public decimal CalculatePay()
        return CurrentEmployee.HourlyRate * TotalHours;

In VB:

Public Class TimeSheet
    Private _CurrentEmployee As Employee
    Public Property CurrentEmployee() As Employee
            Return _CurrentEmployee
        End Get
        Set(ByVal value As Employee)
            _CurrentEmployee = value
        End Set
    End Property

    Private _TotalHours As Decimal
    Public Property TotalHours() As Decimal
            Return _TotalHours
        End Get
        Set(ByVal value As Decimal)
            _TotalHours = value
        End Set
    End Property

    Private _WeekEndingDate As DateTime
    Public Property WeekEndingDate() As DateTime
            Return _WeekEndingDate
        End Get
        Set(ByVal value As DateTime)
            If value > Now.Date Then
                Throw New Exception( _
                "Date must be on or before today’s date")
            End If
            _WeekEndingDate = value
        End Set
    End Property

    Public Function CalculatePay() As Decimal
        Return CurrentEmployee.HourlyRate * TotalHours
    End Function
End Class

The first line defines the class’s scope and name. In this case, the class
is named TimeSheet and is public.

The next set of code defines the private data, called backing fields, and public accessors that provide access to that data. This follows the concept of encapsulation. For example, the private _WeekEndingDate backing field variable contains the value of the time period property. Since this variable is private, it is hidden and cannot be accessed except from within this class. The public WeekEndingDate Property statement implements the get time period and set time period functionality. Any code that needs to set or get the time period uses this public property.

NOTE: The C# code uses auto-implemented properties for the TotalHours and CurrentEmployee. Auto-implemented properties are a short-cut for defining a backing field with its associated accessor. The compiler defines the private backing field for you. You can use auto-implemented properties any time you don’t need extra code, such as validation, in your property statement. (VB is getting auto-implemented properties in VB 10 that is coming with VS 2010.)

By implementing properties using private backing fields and public
Property statements, you can associate code with the setting or retrieval
of the data value. In the WeekEndingDate example, the code that sets the
date validates the date before assigning it.

The code at the end of the class in the preceding example demonstrates
a method—in this case, a function that calculates the pay. In Visual
Basic, methods are implemented with functions or subroutines. In C# the syntax is the same for both functions and subroutines.

To access the properties and use the methods of a class, you normally
begin by creating an instance of the class and storing a reference to that
instance in an object variable. You then use that object variable to get or
set properties and execute methods on the resulting object.
The following code uses the new keyword to create a new object from
the TimeSheet class. It then sets the properties on the object and executes
the CalculatePay method on the object.

In C#:

TimeSheet ts = new TimeSheet();
decimal totalPay;
ts.CurrentEmployee = Jessica; //Jessica is an Employee object
ts.WeekEndingDate = new DateTime(2009, 8, 20);
ts.TotalHours = 51;
totalPay = ts.CalculatePay();

In VB:

Dim ts As New TimeSheet
Dim totalPay As Decimal
ts.CurrentEmployee = Jessica ‘Jessica is an Employee object
ts.WeekEndingDate = #8/20/2009#
ts.TotalHours = 51
totalPay = ts.CalculatePay

The new keyword creates a new instance of the TimeSheet class, and
a reference to that instance is stored in the defined object variable (ts).
Using the object variable and a period, the remainder of the code sets the
object’s properties and calls the method to calculate the pay.

As stated earlier in this section, objects normally maintain state (property
values) and execute methods. The class itself normally does not maintain
state or execute methods. However, .NET does support static
class data and static class methods.

Static class data (also called shared data) is data that the class
retains, independent of any object. Use static class data any time you want
to retain data that is shared between all objects, such as to keep a count of
the total objects created from a class.

A static class method (also called a shared method) is a method
that can be executed independent of any object. Static class methods are
good for utility functions when you don’t need to perform a process on
any particular object. The MessageBox and Debug classes in the .NET
Framework both have static class methods, so you don’t need to create an
instance of the class to use the methods.

NOTE: If you write code in a Visual Basic module instead of a class, all the properties and methods in the module are static. You cannot create an instance from a module.

Building code as individual classes logically separates the code, with
each class defining its own data and implementing its own methods.
Having code organized into logical classes makes finding code for maintenance and enhancements effortless and produces a system that is much easier to extend. It also simplifies testing and debugging, because you can test each class as an independent unit. By using OO, you can manage the complexity of your application.

(Based on an except from "Doing Objects in Visual Basic 2005".)


RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2018 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs