.NET 101
LANGUAGES: VB.NET | C#
ASP.NET VERSIONS: All
VB.NETand C# Programming Basics: Part I
Object-orientedProgramming Concepts
By ZakRuvalcaba
VB.NETand C# are great programming languages because they offer a structured way ofprogramming. By structured, I mean that code is separated into modules, whereeach module defines classes that can be imported and used in other modules.Both languages are relatively simple to get started with, yet offer featuressophisticated enough for complex, large-scale enterprise applications.
Eachlanguage's ability to support more complex applications (its scalability) stemsfrom the fact that it is an object-oriented programming (OOP) language. But askseasoned developers what OOP really is, and they'll start throwing outbuzzwords and catchphrases that are sure to confuse you - terms likepolymorphism, inheritance, and encapsulation. In this article I'm going toexplain the fundamentals of OOP and how good OOP style can help you developbetter, more versatile Web applications down the road. This article willprovide a basic OOP foundation that targets Web developers. In particular,we'll cover the following concepts:
- Objects
- Properties
- Methods
- Classes
- Scope
- Events
- Inheritance
Objects
In OOP,one thinks of programming problems in terms of objects, properties, andmethods. The best way to get a handle on these terms is to consider areal-world object and show how it might be represented in an OOP program. Manybooks use the example of a car to introduce OOP. I'll try to avoid that analogyand use something friendlier: my dog, an Australian Shepherd named Rayne.
Rayne isyour average great, big, friendly, loving, playful mutt. You might describe himin terms of his physical properties: he's gray, white, brown, and black, standsroughly one and a half feet high, and is about three feet long. You might alsodescribe some methods to make him do things: he sits when he hears the command"Sit," lies down when he hears the command "Lie down," and comes when his nameis called.
So, ifwe were to represent Rayne in an OOP program, we'd probably start by creating aclass called Dog. A class describes how certain types of objects lookfrom a programming point of view. When we define a class, we must define thefollowing two things:
- Properties.Properties holdspecific information relevant to that class of object. You can think ofproperties as characteristics of the objects that they represent. Our Dogclass might have properties such as Color, Height, and Length.
- Methods. Methods are actions that objectsof the class can be told to perform. Methods are subroutines (if they don'treturn a value) or functions (if they do) that are specific to a given class.So the Dog class could have methods such as sit and lie_down.
Oncewe've defined a class, we can write code that creates objects of that class,using the class a little like a template. This means that objects of aparticular class expose (or make available) the methods and properties definedby that class. So, we might create an instance of our Dog class called Rayne,set its properties accordingly, and use the methods defined by the class tointeract with Rayne, as shown in Figure 1.
Figure 1: The methods defined by the classinteract with the object.
This isjust a simple example to help you visualize what OOP is all about. In the nextfew sections, we'll cover properties and methods in greater detail, and talkabout classes and class instances, scope, events, and even inheritance.
Properties
As we'veseen, properties are characteristics shared by all objects of a particularclass. In the case of our example, the following properties might be used todescribe any given dog:
In thesame way, the more useful ASP.NET Button class exposes properties,including:
- Width
- Height
- ID
- Text
- ForeColor
- BackColor
Unfortunatelyfor me, if I get sick of Rayne's color, I can't change it. ASP.NET objects, onthe other hand, let us change their properties very easily in the same way thatwe set variables. For instance, we've already used properties when setting textfor the Label control, which is actually an object of the Labelclass in the System.Web.UI.WebControls namespace:
(VB.NET)
lblMyText.Text= "Hello World"
(C#)
lblMyText.Text= "Hello World";
In thisexample we're using a Label control called lblMyText. Remember,ASP.NET is all about controls, and, as it's built on OOP, all control types arerepresented as classes. In fact, all interaction with ASP.NET pages is handledvia controls. When we place a control on a page, we give it a name through itsid attribute, and this ID then serves as the name of the control. Rayneis an object. His name, or ID, is Rayne. Rayne has a height of 18. Thesame holds true for the Label control. The Label control's nameor ID in the previous example is lblMyText. Next, we use the dotoperator (.) to access the Text property that the object exposes and setit to the string "Hello World."
Methods
With ourdog example, we can make a particular dog do things by calling commands. If Iwant Rayne to sit, I tell him to sit. If I want Rayne to lie down, I tell himto lie down. In object-oriented terms, I tell him what I want him to do bycalling a predefined command or method, and a resulting action is performed. InVB.NET or C#, we would write this as rayne.Sit, or rayne.LieDown.
As Webdevelopers, we frequently call methods when a given event occurs. For instance,we can take information from an Access database and create an object called objConnto represent the connection to the database. We then open the connection bycalling the Open method on that object as follows:
(VB.NET)
DimobjConn As NewOleDbConnection( _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"DataSource=C:\Database\books.mdb")
...
objConn.Open()
We saythat the Open method is exposed by the connection object, and that we'recalling the Open method on the OleDbConnection object stored in objConn.We don't need to know what dark secrets the method uses to do its magic; all weneed to know is its name and its purpose.
Classes
You canthink of a class as a template for building as many objects as you like of aparticular type. When you create an instance of a class, you are creating anobject of that class, and the new object has all the characteristics andbehaviors (properties and methods) defined by the class.
In ourdog example, Rayne was an instance of the Dog class, as shown inFigure 2.
Figure 2: A class serves as the blueprintfor an object.
We seethat Rayne is an object of class Dog. In our code, we couldcreate a new instance of the Dog class, call it rayne, and useall the properties and methods exposed by the object.
In OOP,when we create new instances of a class, we say we're instantiating that class.For instance (no pun intended!), if we need to programmatically create a newinstance of the Button control class, we could write the following code:
(VB.NET)
DimmyButton As NewButton()
(C#)
Button myButton = new Button();
As youcan see, we've essentially created a new object called myButton from theButton class. We can then access the properties and methods that Buttonexposes through our new instance:
(VB.NET)
myButton.Text ="Click Me!"
(C#)
myButton.Text ="Click Me!";
Scope
Youshould now have a concept of programming objects as entities that exist in aprogram and are manipulated through the methods and properties they expose.However, in some cases, we want to create methods to use inside our class,which are not available when that class is used in code. Let's return to the Dogclass to illustrate this concept.
Imaginewe're writing the Sit method inside this class, and we realize thatbefore the dog can sit, it has to shuffle its back paws forward a little (bearwith me on this one). We could create a method called ShufflePaws, thencall that method from inside the Sit method. However, we don't want codein an ASP.NET page or in some other class to call this method - it'd just besilly. We can prevent this by controlling the scope of that method.
The twotypes of scope available in VB.NET and C# that you should know about are:
- Public. Defining a property or method of aclass as public allows that property or method to be called from outside theclass itself. In other words, if an instance of this class is created insideanother object (remember, too, that ASP.NET pages themselves are objects),public methods and properties are freely available to the code that created it.This is the default scope in VB.NET and C# classes.
- Private. If a property or method of a classis private, it cannot be used from outside the class itself. If an instance ofthis class is created inside an object of a different class, the creatingobject has no access to private methods or properties of the created object.
Events
Eventsoccur when a control object sends a message in response to some change that hashappened to it. Generally, these changes occur as the result of userinteraction with the control in the browser. For instance, when a button isclicked, a Click event is raised, and we can handle that event toperform some action. The object that triggers the event is referred to as theevent sender; the object that receives the event is referred to as the eventreceiver.
UnderstandingInheritance
Inheritancerefers to the ability of one class to use properties and methods exposed byanother class. In our dog example, we first created a class named Dog,then created instances of that class to represent individual dogs. However,dogs are types of animals, and many characteristics of dogs are shared by all(or most) animals. For instance, Rayne has four legs, two ears, one nose, twoeyes, etc. It might be better, then, for us to create a base class named Animal.When we then define the Dog class, it would inherit from the Animalclass, and all public properties and methods of Animal would beavailable to instances of the Dog class.
Similarly,we could create a new class based on the Dog class. In programmingcircles, this is called deriving a subclass from Dog. For instance, wemight create a class for Australian Shepherd and one for my other dogAmigo, named Chihuahua, both of which would inherit the properties andmethods of the Dog base class, and define new ones specific to eachbreed.
Don'tworry too much if this is still a little unclear. The best way to appreciate inheritanceis to see it used in a real program. The most obvious use of inheritance inASP.NET comes with the technique of code-behind. Part II will continue with alook at using code-behind to separate code from content.
Thisarticle is excerpted from Build Your Own ASP.NET Website Using C#& VB.NET. Getthis book delivered to your doorstep or request additional sample chapters at http://www.sitepoint.com/books/aspnet1/.
Zak Ruvalcaba has been researching, designing, anddeveloping for the Web since 1995. He holds a Bachelor's Degree from San DiegoState University and a Master of Science in Instructional Technology fromNational University in San Diego. Zak has developed Web applications for such companiesas Gateway, HP, Toshiba, and IBM. More recently, he's worked as a wirelesssoftware engineer developing .NET solutions for Goldman Sachs, TV Guide, TheGartner Group, Microsoft, and Qualcomm. He also lectures for the San DiegoCommunity College District on various technologies and tools, includingDreamweaver and ASP.NET.