Microsoft 9GD00001 Computer Accessories User Manual


 
Chapter 3: Learning Just Enough C# and VB.NET: Types and Members 83
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
End Module
Look at where accountBalance is declared: at the beginning of the Program (Module1
in VB) class block. It is at the same scope as Main and other methods, meaning that it is a
member of Program (Module1 in VB), just like Main, Credit, and Debit. When variables
like accountBalance are declared as class members, as opposed to local variables that
are declared inside of method blocks, they are called fields. The accountBalance is type
decimal, which is a good choice for holding financial values.
The accountBalance field has a private modifier, which means that it can only be used by
members of the same class. The implementations of Credit and Debit, respectively, increase
and decrease the value of accountBalance. Since Credit and Debit are members of the same
class as accountBalance, they’re allowed to read from and write to accountBalance.
Main invokes Credit and Debit to change the value of the accountBalance field.
Additionally, Main displays the value of accountBalance in the console window through
a property named CurrentBalance. The next section explains how the CurrentBalance
property works.
Declaring and Using Properties
Properties are class members that you use just like a field, but the difference is that you
can add specialized logic when reading from or writing to a property. Listing 3-8 contains
an example of a property, CurrentBalance, repeated as follows for your convenience:
C#:
public decimal CurrentBalance
{
get
{
return accountBalance;
}