Difference between revisions of "C Sharp Object Oriented Programming"

From Techotopia
Jump to: navigation, search
(Accessing C# Object Members)
(Adding Methods to a C# Class)
Line 155: Line 155:
  
 
Now that we have looked at method class members the next task is to look at two special class methods, the consructor and finalizers.
 
Now that we have looked at method class members the next task is to look at two special class methods, the consructor and finalizers.
 +
 +
== Static, Readonly and Const Data Members ==
  
 
== C# Constructors and Finalizers ==
 
== C# Constructors and Finalizers ==

Revision as of 17:36, 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.

Instantiating an Object from a C# Class

The process of creating an object from the class 'blueprint' is called instantiation. The first step is to create an object variable of the required object type. An instance of the object is then created using the new keyword and assigned to the object variable:

         BankAccount custAccount;

         custAccount = new BankAccount();

It is also poossible to declare the object variable and assign the object in a single statement:

        BankAccount custAccount = new BankAccount();

Now that we have an instance of our BankAccount class the next step is learn how to access the members of the class.

Accessing C# Object Members

Now that we know how to write a class and instantiate objects from the class, we now need to know how to access the memebers of the object. Firstly, you will recall that we declared some members as being public and others as being private. The public methods are fully accessible from outside the object. This is achieved using something called dot notation. Dot notation is a mechanism by which object members may be accessed specifying the object and member names separated by a dot (.). For example, to access the accountName member of an object named custAccount we would reference this member using custAccount.accountName:

using System;

class Hello
{
    public class BankAccount 
    {

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

        static void Main()
        {

		BankAccount custAccount = new BankAccount();

		custAccount.accountName = "John Smith";

		custAccount.accountFee = 5;

		Console.WriteLine ("Customer Name is " + custAccount.accountName);

		Console.WriteLine ("Account Fee = $" + custAccount.accountFee);
        }
}

The above code assigns values to the accountName and accountFee memebrs of our object. It then references the properties in order to display text which reads:

Customer Name is John Smith
Account Fee = $5

This approach works well for public class members, but not for private members. An attempt, for example, to use dot notation to access the private accountNumber member will result in a compilation error along the the lines of:

error CS0122: 'Hello.BankAccount.accountNumber' is inaccessible due to its protection level

In order to access private members we need to provide access methods in the class.

Adding Methods to a C# Class

Class method members are sections of code contained in a class which can be called from outside an object to perform specific tasks. A common types of methods are getter and setter methods which are used to access private data members of a class. For example, we can declare a getter and a setter method to get and set the protected accountNumber member:

public class BankAccount 
{

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

	public int getAccountNumber()
	{
		return accountNumber;
	}

	public void setAccountNumber(int newNumber)
	{
		accountNumber = newNumber;
	}

}

Class methods are called using dot notation. For example, to set the value of the accountNumber:

	BankAccount custAccount = new BankAccount();

	custAccount.setAccountNumber( 12345 );

	Console.WriteLine ("Account Number = " + custAccount.getAccountNumber() );

The above code sets the account number using the setter method and then displays the account number using the getter method.

Now that we have looked at method class members the next task is to look at two special class methods, the consructor and finalizers.

Static, Readonly and Const Data Members

C# Constructors and Finalizers

Despite the grand sounding names, C# class fonstructors and finalizers are nothing more than mehtods which get called when an object is instantiated and destroyed. The constructor is particularly useful for allowing initialization values to be passed through to an object at creation time. Lets say that we would like to be able to initialize the accountName and accountNumber members at the point that we initialize the custAccount object. To do so we need to declare a constructor.

Constructors are declared the same way as other methods with the exception that the name of the mentod must match the class name:

public class BankAccount 
{

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

        // Constructor
	public BankAccount(string acctName, int acctNumber)
	{
		accountName = acctName;
		accountNumber = acctNumber;
        }

        // ....

}

We can now use the constructor to initialize these members at object creation:

	BankAccount custAccount = new BankAccount("Fred Wilson", 123456);

Finalizers are used to clean up any resources used by a class object when the object is destroyed. Unlike constructors which can be triggered from code using the new keyword there is no way to explicitly call a finalizer (for example there is no delete equivalent to the new keyword. Instead, the finalizer will be called when the garbage collector decides that the object instance is no longer needed. All the programmer can be sure of is that the finalizer will be called at some point between the when the object is no longer needed by the code and the point that the application terminates.

Finalizers are defined in the same way as constructors with the exeception that the name is receded by a tilde (~):

        // Finalizer
	public ~BankAccount(string acctName, int acctNumber)
	{
	      // Code to perform clean up
        }