The difference between objects and classes
Creating an object
Setting an object’s properties
Calling an object’s methods
Handling an object’s events
Examples of creating objects from classes in the .NET Framework
In Hour 5, “Understanding Visual Basic’s Variables and Operators,” we looked at using variables and operators in Visual Basic. In Hour 6, “Managing Program Flow with Visual Basic’s Control Structures,” we looked at control structures, such as If
statements, looping constructs, and subroutines and functions. We need to discuss one more important topic regarding Visual Basic before returning to ASP.NET. Specifically, we need to examine how to use objects in Visual Basic.
The key component of an object-oriented programming language like Visual Basic is the object, which is an instance of a class. In this hour we reexamine the relationship between an object and a class and discuss the role of classes and objects in Visual Basic, the .NET Framework, and ASP.NET web pages.
Whether you realize it or not, you’ve already used an assortment of objects in the source code you’ve written in previous hours. Each ASP.NET Web control, for example, exists as an object in the source code portion. When setting the Text
property of a Label control or handling the Click
event of a Button Web control, you are working with objects.
In Hour 2, “Understanding the ASP.NET Programming Model,” we discussed the ideas behind object-oriented programming. To refresh your memory, object-oriented programming is a programming paradigm in which the object is a key construct of the programming language. Objects contain methods, properties, and events. Properties define the state of the object, methods perform actions, and events commonly represent state changes or indicate that some action has transpired.
Recall that in Hour 2 we described object-oriented programming using a car as an analogy. The properties of the car were such things as make, model, and color; its events were stepping on the brakes and turning on the windshield wipers; and its methods were drive, reverse, turn, and so on.
The list of properties, methods, and events that describe a car is referred to as a class, whereas an actual, concrete instance of a car, such as a 2005 silver Porsche Boxster, is referred to as an object.
Classes are the abstractions from which objects are created. To understand the relationship between a class and an object, think of a calculator. A calculator may have properties like current battery power, current value on the screen, last operation entered, and others. It might have methods like add, subtract, and so on. Its events might include clearing the last computation and turning off. If you were to sit down and list all the properties, methods, and events that a calculator has, this list would be equivalent to a class. This list is an abstract idea of what a calculator is and what it does. It clearly is not a concrete representation of a calculator; you cannot use the list to compute the product of 19.34 and 78.
An object, on the other hand, is a concrete representation of the class. The actual calculator that supports the properties, methods, and events outlined by the class is an object and is said to be an instance of the class it represents.
To summarize, a class is an abstract definition, a simple list of properties, methods, and events that are supported. An object, however, is an instance of the class, a concrete “thing” whose properties we can set, whose methods we can call, and whose events can fire.
Recall from our earlier discussions that the .NET Framework contains a plethora of classes that allow for a variety of functionality. For example, each and every Web control that can be used in an ASP.NET page is represented by a class in the .NET Framework.
Classes in the .NET Framework allow for an email to be sent from a web page, for data to be retrieved from a database, for an image to be created, and so on. The code in your ASP.NET pages can utilize the variety of functionality present in the .NET Framework.
To use one of the classes in the .NET Framework, we first must create an object from the particular class whose functionality we are interested in. After we have an object, we may need to set some of the object’s properties and call some of its methods. Additionally, we may need to create event handlers for some of its events.
When using objects, we’ll perform four tasks again and again:
Instantiation—. Before we can work with an object, we need to create an instance of the object from the desired class. This is a required step that must be performed before working with an object.
Setting property values—. In most scenarios we will need to set one or more properties of the object we’re working with. Remember that properties are values that describe the state of the object. For example, a class that represents an email message might have properties like Body
, Subject
, To
, From
, Cc
, and forth.
Calling methods—. When using objects, we will always call one or more of the object’s methods. A class that sends email messages, for example, might have a method called Send
that sends a specified email message. To send an email using this class, we would first create an instance of the class; then set its Body
, Subject
, To
, From
, and other pertinent properties; and then call its Send
method.
Creating event handlers—. In some cases we will need to run a set of instructions only when a particular event for a particular object fires. This can be accomplished by creating an event handler that’s wired up to the object’s pertinent event. We’ve created event handlers for a Button Web control’s Click
event and for the page’s Load
event in previous hours.
The remainder of this hour examines the Visual Basic syntax required to accomplish these four tasks.
In addition to properties, methods, and events, classes contain constructors. A constructor is a special method that is used to create an instance of the class.
In a later section, “Calling an Object’s Methods,” we’ll discuss what, exactly, methods are. For now, you can think of a method as a function or subroutine. Like functions and subroutines, methods are a means of encapsulating a number of program instructions; they can have zero or more parameters and may return a value.
Constructors always have the same name as the class. For example, one of the classes used to programmatically work with database data is the SqlCommand
class. The constructor for this class is a method named SqlCommand
.
To create an instance of an object, use the following syntax:
Variable = New Constructor()
The constructor Constructor
creates and returns an object from the class named Constructor
. Because Visual Basic is a strongly typed language, the type of Variable
must be the same type as the class whose constructor is being called. For example, to create an instance of the SqlCommand class, we would first create a variable whose type was of SqlCommand
as follows:
Dim MyCommand as SqlCommand
Then we would assign to this variable the object returned by the constructor:
MyCommand = New SqlCommand()
The first line of code creates a variable named MyCommand
of type SqlCommand
. The second line of code calls the constructor, creating a new SqlCommand
object; this new object is then assigned to MyCommand
.
Before working with an object, we must first create an instance of the object. This process is commonly called instantiation. We can instantiate an object like this:
Dim Variable as type Variable = New Constructor()
Or by combining the two statements on one line, like this:
Dim Variable as type = New Constructor()
For example, the following code declares a variable named MyCommand
and assigns to it a new SqlCommand
object:
Dim MyCommand as SqlCommand = New SqlCommand()
Constructors, like functions and subroutines, can have zero or more parameters. Additionally, classes may have more than one constructor. When constructors accept one or more parameters, the parameter values are typically used to specify initial values for the classes’ various properties. For example, the SqlCommand
class has a constructor that accepts zero parameters, as well as one that accepts a string parameter. The constructor that accepts zero parameters does not assign any initial value to any of its properties. The constructor that accepts a string parameter, however, assigns the passed-in parameter value to the object’s CommandText
property.
In general, any class method (such as the constructor) can have multiple versions; each accepts a different number of input parameters. A single method that has multiple versions that accept different numbers of parameters are referred to as overloaded.
Constructors that accept more than one parameter are used for reducing the amount of code that needs to be written. For example, to create a SqlCommand
object and set its CommandText
property, we need to use the following two lines of code:
Dim MyCommand as SqlCommand = New SqlCommand() MyCommand.CommandText = "some value"
However, by using the SqlCommand
constructor that accepts a string parameter, we can condense these two lines into one:
Dim MyCommand as SqlCommand = New SqlCommand("some value")
After creating an object, we may need to set some of its properties. To reference an object’s properties, use the following syntax:
ObjectVariable.PropertyName
Here, ObjectVariable
is the name of the object variable. That is, in the code
Dim myCommand as SqlCommand myCommand = New SqlCommand()
the ObjectVariable
is myCommand
. The PropertyName
is the name of the property that you want to access. Properties are used just like variables; they can be assigned values, they have types, and they can be used in expressions.
Typically, you assign a value to a property just once and then call one of the object’s methods, which uses the value of the property in some manner.
For example, to send an email message from an ASP.NET page, we use the MailMessage
class. When an instance of this class is created, a number of properties need to be set, such as From
, To
, Subject
, and others. The following code snippet demonstrates how to create an instance of this class and set its properties:
'Create an instance of the MailMessage class Dim MyMailMessage As MailMessage = New MailMessage() 'Set the From, To, Subject, and Body properties MyMailMessage.From = "[email protected]" MyMailMessage.To = "[email protected]" MyMailMessage.Subject = "Email Subject" MyMailMessage.Body = "Hello!"
Not all properties can necessarily be written to and read from. Some classes mark certain properties as read only or write only. The vast majority of properties, however, are both readable and writeable. When examining a new class and its properties, I’ll point out whether any properties are read only or write only.
An object’s methods are called just like other subroutines and functions, except that the name of the object whose method you want to call must precede the method name. That is, the syntax for calling an object’s method is as follows:
ObjectVariable.MethodName(param1, param2, ..., paramN)
Methods in classes are semantically equivalent to subroutines and functions. Methods in classes can accept zero to many input parameters and can optionally provide a return value.
As we discussed earlier, the SqlCommand
class is used for programmatically working with database data. In using the SqlCommand
class, we must specify the database to retrieve the data from, as well as what data to retrieve. These two bits of information are specified via the Connection
and CommandText
properties. The SqlCommand
class’s ExecuteReader
method, when executed, returns the data specified by the CommandText
property from the database specified by the Connection
property.
Before calling the ExecuteReader
method, we first must create an instance of the SqlCommand
class and set its Connection
and CommandText
properties. The following code snippet demonstrates the syntax for calling a method:
'Create an instance of the SqlCommand class Dim MyCommand as SqlCommand = New SqlCommand() 'Set the Connection and CommandText properties MyCommand.Connection = ... MyCommand.CommandText = "..." 'Call the ExecuteReader() method Dim MyReader as SqlDataReader MyReader = myCommand.ExecuteReader()
As you can see in this code snippet, the ExecuteReader
method returns an object of type SqlDataReader
. This SqlDataReader
object contains the data specified by the CommandText
property.
Methods that return a value are similar to functions; some methods do not return a value, making them similar to subroutines. Also, methods—both ones that do and ones that do not return a value—can have zero to many input parameters.
In addition to methods and properties, objects may also have events. Events typically represent a state change or indicate that some action has transpired. For example, the ASP.NET Button Web control has a Click
event that indicates that the user has performed some action, namely that she’s clicked the button in her browser. A good example of an event representing a state change is the TextBox Web control’s TextChanged
event, which is fired on postback if the TextBox’s text content has been changed.
In many scenarios, we will need some code that we’ve written to run in response to a particular event firing. To accomplish this, we must create an event handler. An event handler is a subroutine with a particular set of input parameters that is wired to a particular event. This wiring process, which we’ll examine shortly, causes the event handler to be executed whenever the event is raised.
All event handlers in a .NET program must be created as a subroutine and must accept precisely two input parameters: the first one must be of type Object
and the second must be of a type derived from EventArgs
. For example, the event handler for a Button Web control’s Click
event (which Visual Web Developer can create for us automatically) has the following signature:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click ... End Sub
This statement defines a subroutine named Button1_Click
that serves as an event handler for Button1
’s Click
event.
As you can see, the first parameter passed into the event handler named sender
is of type Object
. When an event is raised, the object that raised the event is passed in as sender
. The second parameter is of type EventArgs
. This second parameter can contain additional event-related information. In this event handler, as well as the Page_Load
event handler, no additional information is passed in. However, in future hours we will see examples of event handlers that are sent additional information through this second input parameter.
Along with these two input parameters, the event handler’s definition includes the Handles
keyword. This keyword is responsible for wiring the event handler to a particular event. In the case of the Button1_Click
event handler, the subroutine is wired to Button1
’s Click
event. Button1
is an object representing the Button Web control defined in the page’s HTML portion with ID Button1
.
You can create an event handler in Visual Basic by typing in the appropriate syntax by hand. However, Visual Web Developer can autogenerate event handler syntax for you. As we saw in previous hours, double-clicking a Web control in the Design view creates an event handler for the Web control’s default event. Alternatively, you can go to the source code portion and select the appropriate object and event from the drop-down lists at the top.
In this hour we reexamined the concepts behind objects and classes. To use an object, we first must create it. This is accomplished using the Visual Basic New
keyword along with a constructor. As we saw, a constructor is a method that has the same name as the class and returns an instance of the class. For example, to create an instance of the SqlCommand
class, we could use
Dim MyCommand as SqlCommand MyCommand = New SqlCommand()
After an object has been created, we can set its properties, call its methods, and create event handlers. An object’s properties are accessible by listing the object’s name, followed by a period (.
), followed by the property name. For example, to access the CommandText
property of the MyCommand
object, we would use the following syntax:
MyCommand.CommandText
Properties have the same semantics as ordinary variables; they have a type and can be used in expressions or assigned values.
An object’s methods are called by listing the object’s name, followed by a period, followed by the method’s name. Methods are like subroutines and functions in that they may accept zero or more input parameters and can optionally return a value.
Objects can also have a number of events that fire at different times during the object’s lifetime; when an event fires, we may want to execute some code. Event handlers are special subroutines that are wired up to a particular event and execute when that specified event fires. Event handlers must accept two input parameters and use the Handles
keyword to indicate the particular event that they execute in response to. Although an event handler’s syntax can be entered manually, Visual Web Developer will easily create the appropriate event handler syntax: just specify the object and event from the drop-down lists at the top of the source code portion of an ASP.NET page.
This hour concludes our in-depth examination of Visual Basic. In the next hour we will look at the two ASP.NET Web controls that are used for displaying text: the Label and Literal Web controls. Following that, we spend the next several hours examining how to collect and process user input.
This hour showed us how to use classes in the .NET Framework, but is it possible to create our own classes? | |
With object-oriented programming languages like Visual Basic, you can create your own classes. However, doing so is beyond the scope of this book. Although we’ll be using a number of the .NET Framework classes throughout the course of this book, won’t ever need to create our own classes. | |
Will we be examining how to send email messages from an ASP.NET page in this book? | |
No, I’m afraid we won’t have the time to dissect sending an email message from an ASP.NET page. However, a plethora of online articles show how to accomplish this common task. The two classes used in ASP.NET 3.5 for sending email messages are the |
18.225.175.151