
84Microsoft Visual Studio 2010: A Beginner’s Guide
set
{
if (value < 0)
{
// charge fee
}
accountBalance = value;
}
VB:
Public Property CurrentBalance() As Decimal
Get
Return accountBalance
End Get
Set(ByVal value As Decimal)
If value < 0 Then
'charge fee
End If
accountBalance = value End Set
End Property
Properties have accessors, named get and set, that allow you to add special logic when the property is used. When you read from a property, only the get accessor code executes, and the set accessor code only executes when you assign a value to a property. In the preceding example, the get accessor returns the value of currentBalance with no modifications. If there were some logic to apply, like calculating interest in addition to the current balance, the get accessor might have contained the logic for that calculation prior to returning the value. The set accessor does have logic that checks the value to see if it is less than zero, which could happen if a customer overdrew his or her account. If the value is less than zero, then you could implement logic to charge the customer a fee for the overdraft. The value keyword contains the value being assigned to the property, and the previous set accessor assigns value to the accountBalance field. The following statement from the Main method in Listing
C#:
Console.WriteLine("Balance: " + account.CurrentBalance);
VB:
Console.WriteLine("Balance: " & CurrentBalance)