OOP in .NET: the How and Why ByPeter Aitken 2004-12-12
Article Rating: / 2
Rate This Article:
Add This Article To:
New to .NET or to object-oriented programming? With this article, Peter Aitken begins a three-part series on the basics.
Object oriented programming, or OOP for short, is nothing new. It has been around for quite a while, and has long been recognized as having many significant advantages over other programming paradigms (more about this soon). Early OOP languages, such as Smalltalk, had their devoted adherents, but never really caught on in the mainstream development world. Some aspects of OOP made their way into popular languages, such as Visual Basic "classic", but they lacked all the features that make OOP such a powerful development technique.
The first truly object-oriented development tool for the Windows platform was Microsoft Visual C++, and for many years this was the programming tool of choice for many if not most developers doing heavy-duty work. C++ is not, however, an easy or elegant language and is perhaps best viewed as the first step in the evolution of OOP for the Windows platform.
ADVERTISEMENT
If C++ was the first step, what's the second? That's easy — with Visual Studio.Net, the power of OOP has been brought to two new, or at least improved, languages: Visual Basic and C# (say "C sharp"). Visual Basic.Net is our old friend with some modest changes required to meet the needs of .Net's Common Language Runtime and an object-oriented structure, while C# seems to be an amalgam of the best parts of C, C++, and Java (not everyone sees it that way, of course) that is much easier to learn and use than C++.
What does this mean to you, Joe or Jane Q. Programmer? You can now use OOP techniques in your programs and gain all the advantages without necessarily being a certified geek. Before you can get started, however, it helps to have an understanding of OOP principles and how exactly it is implemented in .Net, and this article will give you just that.
Be aware that the .Net Framework itself consists of a rich assortment of objects, already defined and ready to be used in your programs. This is, of course, essential to .Net programming, but it's not what I'll talking about here, which is writing the code to define and use your own objects.
This is the first of three articles on this topic. I will use Visual Basic.Net syntax for the examples, but note that the process in C# is essentially the same, with only some keyword differences.
Classes and Objects
Another term you'll hear frequently used in OOP is class. A class is related to an object in the same way that a blueprint for a toaster is related to an actual toaster. A class, in other words, is a plan for an object. A class exists as source code that you or someone else has written. An object does not exist until a program creates it from a class. When a program creates an object it is called instantiating the class, and an object is
sometimes called an instance of the class. A program can create as many instances of a given class as it needs, just like you can create one, two, or a hundred toasters from the blueprints. Each instance is fundamentally the same as the others but is independent of all other instances.
OOP Basics and Advantages
At the heart of OOP is the idea that a program can be broken into independent functional units — objects — that are walled off from each other. Each object has a set of carefully designed inputs and outputs through which it interacts with the rest of the program, but otherwise what goes on within the object is completely isolated from the rest of the program. These inputs and outputs are called the object's interface. There are two
types of inputs and outputs:
A property is an item of data that is stored within the object. You can think of a property as a variable that is part of an object, although you'll see that properties are a lot more powerful than traditional variables.
A method is an action that the object can perform. In many ways a method is a procedure (function) that is part of an object.
I mentioned that objects are by their nature isolated from the rest of the program, and this is one of their main advantages. The earlier programming paradigm, called procedural programming, does not have this advantage. Procedural programming is still widely used (for example, Visual Basic "classic") and, like OOP, is based on the idea of dividing a program into functional units called procedures (or functions). Despite the power of this approach it has the weakness that the units — procedures — are not inherently walled off from each other. In programs written with a procedural language,
particularly large, complex programs, unintended interactions between different parts of the program are a major cause of bugs and errors and also can vastly increase the difficulty of program modifications and upgrades. While OOP is not a panacea for these problems, it does make the developer's life a lot easier.
Defining a Class
A class is defined within the Class...End Class block:
Public Class Classname
...
End Class
Within this block, you place the code for all of the class's components, such as properties and methods. The class will be part of whatever namespace the definition is placed within (that is, a Namespace...End Namespace block). Class names follow the usual naming rules for variables and must be unique within the namespace. Note that you must not use the name MyClass because it is a Visual Basic keyword. The Public keyword makes the class available in the project without restrictions. Class access can be restricted in various ways, but these are specialized situations that are beyond the scope of this article. Public is what you want to use in most cases.
In Visual Studio you can use the Project|Add Class command to add a new class to your project. The drawback of this method is that it creates a separate file for each class, and when you have a lot of classes in a project this can be unwieldy. You can define a class just about anywhere in your project's source code, and my preference is to add a module to the project and place all the class definitions there.
Instantiating a Class
To use a class — that is, to create an object based on the class — you use the New keyword. It's exactly the same for instantiating a class you defined as for any other class, such as those in the .Net Framework. You can declare a variable to hold the object reference and create the object in one statement as shown here:
Dim MyClassVar As New ClassName
You can also separate the declaration and creation steps like this:
Dim MyClassVar As ClassName...
MyClassVar = New ClassName
To create an array of objects, the syntax is the same as creating an array of any other type. For example:
Dim MyArray(100) As MyClassName
Then, each array element must be instantiated. You could do this one at a time:
MyArray(0) = New MyClassName
Or you could create a loop to instantiate all the array elements:
For i = 0 to 100
MyArray(i) = New MyClassName
Next
If you have used the old Visual Basic you may be wondering where the Set keyword is. It's gone, that's where! There is no need to use Set when assigning object references in Visual Basic.Net.
When your program is done using an object, it's a good idea to set the object reference to Nothing:
MyClassVar = Nothing
This is called dereferencing and marks the object for .Net's garbage collection process, which frees the memory and other resources that the object used. When an object variable goes out of scope, it is automatically dereferenced. For example, if the object variable was declared and instantiated within a method or procedure, it is dereferences automatically when execution leaves the method or procedure and you need not explicitly set it to Nothing, although doing so does no harm.
When to Use Objects
One problem faced by programmers who are new to OOP is the simple question of when to use objects and when they are not appropriate. The fact is that there are few if any situations where you could not use OOP to good advantage. After all, any code that you could use outside of an object can also be placed within a class. It does take a bit of time to adjust to the OOP mindset so that you start thinking in terms of classes and objects as soon as you start planning a program. As you plan, think of the program's functionality in terms of both data storage and actions, and you'll start to see some of the data units and tasks that are naturals for encapsulation in a class.
In the next article in this series, I'll continue with the details of creating and using your own classes.