Setting an Object s Properties


Setting an Object's Properties

After we have created an object, often we want to set some of the object's properties. To reference an object's properties, we use the following syntax:

objectVariable.PropertyName 


Here, objectVariable is 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 just like variables.

Typically, you will assign a value to a property just once and then will 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 MailMesage class Dim myMailMessage As MailMessage = New MailMessage() 'Set the From, To, Subject, and Body properties myMailMessage.From = "someone@example.com" myMailMessage.To = "someone@example.com" myMailMessage.Subject = "Email Subject" myMailMessage.Body = "Hello!" 


By the Way

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 if any of those properties are read only or write only.





Sams Teach Yourself ASP. NET 2.0 in 24 Hours, Complete Starter Kit
Sams Teach Yourself ASP.NET 2.0 in 24 Hours, Complete Starter Kit
ISBN: 0672327384
EAN: 2147483647
Year: 2004
Pages: 233

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net