Microsoft.NET

……………………………………………….Expertise in .NET Technologies

Introduction (OOP’s in C#) – Part 1

Posted by Ravi Varma Thumati on July 10, 2009

OOP stands for Object-Oriented Programming. OOP is relatively a new way to program computer applications. Before OOP, programmers are used to creating computer applications using procedural-programming (or structure-programming) but when OOP solved a lot of the problems of the procedural-programming almost all of the programmers and developers began using OOP languages.

In procedural- programming all the program functionality written in a few modules of code or maybe one module (depending on the program) and these modules depend on one another and if you want to change a line of code you will have to rewrite the whole module again and maybe the whole program but in Object-Oriented Programming programmers write independent parts of a program called classes and each class represent a part of the program functionality and these classes can be assembled to form a program and when you need to change some of the program functionality all you have to do is to replace the target class which may contain a problem. So in OOP applications create by the use of classes and these applications can contain any number of classes. That will get us to discuss the Class and Object concept.

  • Object oriented programming is used to organize the code and refine it in the application
  • It prevents the code redundancy
  • It makes the code readable, reusable and reliable
  • It enables us to maintain the program code, modify it, and easy to determine any exceptions

Key Concepts of Object Orientation

  • Objects, Classes
  • Encapsulation
  • Polymorphism
  • Abstraction
  • Inheritance
  • Interface.

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.

Object References

When we work with an object we are using a reference to that object. On the other hand, when we are working with simple data types such as Integer, we are working with the actual value rather than a reference.

When we create a new object using the New keyword, we store a reference to that object in a variable. For instance:

Draw MyDraw = new Draw;

This code creates a new instance of Draw. We gain access to this new object via the MyDraw variable. This variable holds a reference to the object.

Now we have a second variable, which also has a reference to that same object. We can use either variable interchangeably, since they both reference the exact same object. The thing we need to remember is that the variable we have is not the object itself but, rather, is just a reference or pointer to the object itself.

Early binding means that our code directly interacts with the object, by directly calling its methods. Since the compiler knows the object’s data type ahead of time, it can directly compile code to invoke the methods on the object. Early binding also allows the IDE to use IntelliSense to aid our development efforts; it allows the compiler to ensure that we are referencing methods that do exist and that we are providing the proper parameter values.

Late binding means that our code interacts with an object dynamically at run-time. This provides a great deal of flexibility since our code literally doesn’t care what type of object it is interacting with as long as the object supports the methods we want to call. Because the type of the object isn’t known by the IDE or compiler, neither IntelliSense nor compile-time syntax checking is possible but we get unprecedented flexibility in exchange.

If we enable strict type checking by using Option Strict On at the top of our code modules, then the IDE and compiler will enforce early binding behavior. By default, Option Strict is turned off and so we have easy access to the use of late binding within our code.

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 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 any 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 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 is 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 we need to look briefly at a few additional data member types, and then learn how to create object instances from the class.

Static, Read-only and Const Data Members

In addition to the types of data member types we have looked at so far, C# also provides support for a number of additional member types. C# static member types (also referred to as class properties) are used to store data values which are common to all object instances of class. For example, all bank customers would likely earn the same rate of interest on a savings account. An interestRate member would, therefore, be declared as static since it is common across all object instances of the class.

Static members are declared using the static keyword. For example:

public class BankAccount

{

public static int interestRate;

}

Static members are accessed through the class, not though the object. For example we would change the interestRate member for all object instances by reference the BankAccount class as follows:

BankAccount.interestRate = 10;

For data members that must not be modified the const and readonly keywords are provided by C#. Both achieve the same objective of preventing the value assigned to a data member from being changed after it has been declared. The value of a const or readonly member must be assigned at creation time:

public readonly daysInWeek = 7;

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 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 members 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 by 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 members 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 Class

Class method members are sections of code contained in a class which can be called from outside an object to perform specific tasks. 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 constructor and finalizers.

Encapsulation

Encapsulation, also known as data hiding, is an important object-oriented programming concept. It is the act of concealing the functionality of a class so that the internal operations are hidden, and irrelevant, to the programmer. With correct encapsulation, the developer does not need to understand how the class actually operates in order to communicate with it via its publicly available methods and properties; known as its public interface.

Encapsulation is essential to creating maintainable object-oriented programs. When the interaction with an object uses only the publicly available interface of methods and properties, the class of the object becomes a correctly isolated unit. This unit can then be replaced independently to fix bugs, to change internal behaviors or to improve functionality or performance.

For Example

In the car analogy this is similar to replacing a headlight bulb. As long as we choose the correct bulb size and connection (the public interface), it will work in the car. It does not matter if the manufacturer has changed or the internal workings of the bulb differ from the original. It may even offer an improvement in brightness!

Passing Messages

Message passing, also known as interfacing, describes the communication between objects using their public interfaces. There are three main ways to pass messages. These are using methods, properties and events. A property can be defined in a class to allow objects of that type to advertise and allow changing of state information, such as the ‘TopSpeed’ property. Methods can be provided so that other objects can request a process to be undertaken by an object, such as the Steer () method. Events can be defined that an object can rise in response to an internal action. Other objects can subscribe to these so that they can react to an event occurring. An example for vehicles could be an ‘ImpactDetected’ event subscribed to by one or more ‘AirBag’ objects.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: