Changes

C Sharp Object Oriented Programming

2,185 bytes removed, 17:24, 18 January 2008
Defining Class Methods
BankAccount custAccount = new BankAccount("Fred Wilson", 123456);
</pre>
 
== Defining Class Methods ==
 
Since we have declared our our class data properties to be private, we need to provide methods which will give us access to those properties from our code. This is achieved using Get and Set methods. The syntax for get and Set methods is as follows:
 
'''Public Property''' ''propertyName()'' '''As''' ''datatype''<br>
&nbsp;&nbsp;&nbsp;'''Get'''<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;''.... Code to return property value''<br>
&nbsp;&nbsp;&nbsp;'''End Get'''<br>
<br>
&nbsp;&nbsp;&nbsp;'''Set(ByVal''' ''value'' '''As''' ''datatype'' ''')'''<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;''.... Code to return property value''<br>
&nbsp;&nbsp;&nbsp;'''End Get'''
 
To demonstrate this we will add to our class to provide methods to get and set the account number and name. Note that after you type in the ''Public Property'' line of the declaration, Visual Studio automatically creates a template for the Get and Set methods, which should be filled in as follows:
 
<pre>
Public Class clsBankAccount
Private strAccountNumber As String
Private strAccountName As String
Private intBalance As Integer
Private accountFee As Integer = 5
 
Public Property AccountName() As String
Get
 
End Get
Set(ByVal value As String)
 
End Set
End Property
 
Public Property Balance() As Integer
Get
Return intBalance
End Get
Set(ByVal value As Integer)
intBalance = value
End Set
End Property
End Class
</pre>
 
Now that we have defined our getter and setter methods we can add our own method to perform task. This is the same as writing a Visual Basic function. The purpose of our method will be to subtract the account fee from the current balance:
 
<pre>
Public Function subtractFee() As Integer
intBalance = intBalance - intAccountFee
Return intBalance
End Function
</pre>
 
When called, the above function subtracts the account fee from the balance, assigns thje new balance the intBalance variable and returns the new total.
 
Now that we have added some functionality to our class it is time to instantiate objects from the class ''blueprint''.