Chapter 3: Learning Just Enough C# and VB.NET: Types and Members

85

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.

Many of the properties you’ll write will simply be wrappers around current object state with no other logic, as in Listing 3-9.

Listing 3-9 Property that wraps object state with no logic

C#:

private string m_firstName;

public string FirstName

{

get

{

return m_firstName;

}

set

{

m_firstName = value;

}

}

VB:

Private m_firstName As String

Public Property FirstName() As String Get

Return m_firstName End Get

Set(ByVal value As String) m_firstName = value

End Set End Property

In Listing 3-9, you can see that m_firstName, commonly referred to as a backing field, is a private variable and that the FirstName property only returns m_firstName from the get accessor and assigns the value to m_firstName in the set accessor. Since this is so common, you can save syntax by using an automatic property, as shown in Listing 3-10.

Page 108
Image 108
Microsoft 9GD00001 manual Listing 3-9 Property that wraps object state with no logic