Wednesday, February 9, 2011

Using Properties in .Net

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.example of a property,
"CurrentBalance"
C#:
public decimal CurrentBalance
{
get
{
return accountBalance;
}
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
  • 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  reads from CurrentBalance, effectively executing the
get accessor, which returns the value of currentBalance:
C#:
Console.WriteLine("Balance: " + account.CurrentBalance);
VB:
Console.WriteLine("Balance: " & CurrentBalance)
Since the CurrentBalance property returns the value of the accountBalance field,
the Console.WriteLine statement will print the value read from CurrentBalance to the
command line.

No comments :

Post a Comment