Difference between revisions of "C Sharp Object Oriented Programming"

From Techotopia
Jump to: navigation, search
(Creating C# Class Members)
(Instantiating an Object from a Visual Basic Class)
Line 106: Line 106:
 
Now that we have added some functionality to our class it is time to instantiate objects from the class ''blueprint''.
 
Now that we have added some functionality to our class it is time to instantiate objects from the class ''blueprint''.
  
== Instantiating an Object from a Visual Basic Class ==
 
  
The process of creating an object from the class 'blueprint' is called instantiation. Essentially, you instantiate an instance of the class and give that instance a name by which you will refer to it when accessing members and calling methods. You can create as many object instances of a class as you desire. Objects are instantiated from a class using the ''new'' keyword. Visual Basic provides two ways to instantiate an object from a class. These two alternatives are known as late-binding and early binding.
 
 
Late binding occurs when the assignment of the object to the variable occurs at run-time when execution reaches the code where the object is created. There are drawbacks to this approach in that  any syntax checking is not performed until the application runs because the compiler has no way of checking whether you are referencing valid class members, resulting in potential run-time exceptions. Another disadvantage is that execution can be slowed when using late-binding since much of the work performed by the compiler when using early binding has to be performed at runtime.
 
 
Late binding is achieved using the ''new'' keyword as follows:
 
 
<pre>
 
Dim objBankAccount As Object
 
 
objBankAccount = New clsBankAccount()
 
</pre>
 
 
Early binding, on the other hand, has none of the draw backs of late-binding. The compiler performs syntax checks to ensure the object is being used correctly and execution speed is increased because the binding takes place at compile time - not at run-time.
 
 
Early binding is performed as follows:
 
 
<pre>
 
Dim objBankAccount As clsBankAccount
 
 
objBankAccount = New clsBankAccount
 
</pre>
 
 
It is also possible to instantiate the object at the same time that it is declared:
 
 
<pre>
 
Dim objBankAccount As New clsBankAccount()
 
</pre>
 
  
 
== Accessing Object Properties and Methods ==
 
== Accessing Object Properties and Methods ==

Revision as of 16:39, 18 January 2008

So far in C# Essentials we have looked at the basics of programming in C# such as variable types and flow control. Although it would be possible to write a functional program using these techniques, there is more more to becoming a proficient C# programmer. C# is, above all, an object oriented programming language and as such any C# programmer will be expected to create object-oriented applications using this language.

C# provides extensive support for developing object-oriented applications. The subject area of object oriented programming is, however, large. It is not an exaggeration to state that entire books could be dedicated to the subject (because entire books have been dedicated to the subject). As such, a detailed overview of object oriented software development is beyond the scope of C# Essentials. Instead, we will introduce the basic concepts involved in object oriented programming and then move on to explaining the concept as it relates to C# application development.


Contents


What is an Object?

An object is a self-contained piece of functionality that can be easily used, and re-used as the building blocks for a software application.

Objects consist of data variables and functions (called methods) that can be accessed and called on the object to perform tasks. These are collectively referred to as members.

What is a Class?

Much as a blueprint or architect's drawing defines what an item or a building will look like once it has been constructed, a class defines what an object will look like when it is created. It defines, for example, what the methods will do and what the member variables will be.


Declaring a C# Class

Before an object can be instantiated we first need to define the class 'blueprint' for the object. In this chapter we will create a Bank Account class to demonstrate the concepts of C# object oriented programming.

A C# class is declared using the public class keywords followed by the name of the class. Although the C# compiler will accept just about nay name for a class, programming convention dictates that a class name begin with a capital letter:

public class BankAccount
{

}

We have now defined a class which currently contains no members. The next task, therefore, is to add some members.

Creating C# Class Members

Class members or properties are essentially variables and methods embedded into the class. Members can be public, private or protected.

public members can be accessed from outside the object and are also visible in classes derived from the current class. private members can only be accessed by methods contained in the class and are not accessible to derived classes. protected classes are only available to derived classes.

This the key to what is called data encapsulation. Object-oriented programming convention dictates that data should be encapsulated in the class and accessed and set only through the methods of the class (typically called getters and setters).

We can now extend our BankAccount class to add member variables to hold the account name and number. True to the concept of data encapsulation we will be making some of these creating members private and writing methods to access these values later:

public class BankAccount 
{

	public string accountName;
        public int accountFee;
	private int accountBalance;
	private int accountNumber;
}

Now that we have defined the properties of our class, the next task is to learn how to create an object from the class and access some of the class members.

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
   Get
     .... Code to return property value
   End Get

   Set(ByVal value As datatype )
     .... Code to return property value
   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:

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

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:

    Public Function subtractFee() As Integer
        intBalance = intBalance - intAccountFee
        Return intBalance
    End Function

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.


Accessing Object Properties and Methods

Now that we know how to write a class and instantiate objects from the class, we now need to know how to call the methods on the methods we created in the class. First, you will recall that we created Get and Set functions the data members of our class. Because we did this, we can change and access these properties simply by reference them as we would any other property. For example:

Dim objBankAccount As New clsBankAccount()

objBankAccount.AccountName = "John Smith"

objBankAccount.Balance = 1230

MessageBox.Show(objBankAccount.AccountName & " has a balance of " & CStr(objBankAccount.Balance))

The above code excerpt assigns values to the AccountName and account balance properties of our object. It then references the properties in order to display a string with reads "John Smith has balance of 1230" in a MessageBox.

We can also call our subtractFee() method as follows:

Dim objBankAccount As New clsBankAccount()
Dim intNewbalance As Integer

objBankAccount.AccountName = "John Smith"
objBankAccount.Balance = 1230

intNewbalance = objBankAccount.subtractFee()

MessageBox.Show(objBankAccount.AccountName & " has a balance of " & CStr(objBankAccount.Balance))

The result will be a message which reads "John Smith has balance of 1225", since the account fee has now been subtracted from the balance.