Wednesday 11 January 2012

Understanding CSharp and VB.NET as Object Oriented Programming languages

After knowing the object-oriented concepts let us examine how these concepts can be implemented in CSharp (C#) or VB.NET. These two languages are been introduced along with the .NET framework and are totally .NET compliant. So VB.NET will be a natural upgrade for VB programmers and CSharp for C++
programmers. We will be looking at the various syntaxes of both these languages to implement object  oriented programming.

Classes
As we have discussed earlier classes are going to be an integrated unit consisting of the data and the functions that would act upon the data.
The Employee class would be something like this:
VB.Net
Public Class Employee
Dim Empid As Integer
Dim EmpName As String
Dim EmpAddress As String
Dim Basic As Double
Public Sub AddDetails ()
---------
---------
End Sub
Public Sub PrintDetails ()
---------
---------
End Sub
Public Sub CalcSalary ()
---------
---------
End Sub
End Class


C#
public class Employee
{
int Empid;
string EmpName;
string EmpAddress;
double Basic;
public void AddDetails ()
{
---------
---------
}
public void PrintDetails ()
{
---------
---------
}
public void CalcSalary ()
{
---------
---------
}
}
   The attributes in our employee entity are defined as data members and the functionalities would be the member functions. So our classes happen to be independent entities in our application. Dependant upon the application the number of classes in the application might vary. We need to be a bit careful about the design of our classes specifically when we decide the data members and the member functions. We will have to ensure complete atomicity and that no class would be allowed to access the data of any other class unless it’s a
strict constraint in the design of the classes.
   Then just by declaring he class we have laid down a specification. The class would be actually in form or will be allocated memory only when we create an instance of that class i.e. creating an “object” of the class. Therefore, a class is just a blue print of an entity, which just tells what does the entity have, and how
does the entity behave.

   Based upon the program requirement we can have this object created either at compilation time (stack segment of the process memory) or at runtime (on the heap). But if the object is created at runtime it will also be necessary to deallocate the object to avoid a memory leak. .NET framework provides us with an
automatic memory management system. In addition, for this system to monitor our memory its mandatory to have all our objects created at runtime. Hence, in .NET scenario we are going to have only heap-based objects, which would get created at runtime.
   At times we might in our application require multiple instances of the same class. The multiple objects of the class are going to have only their set of data members and they would share the copy of member functions. Then how would the data of the appropriate object get modified. As like any other programming language, the .NET languages also support the “this” reference, which would be an implicit argument of every function (non static function). This reference contains the address of the object through which the function was called.
    Just as an application would require multiple instances of a same class an application also might require objects of different classes. These classes might be from different libraries. There are high chances that two different libraries might have a class of the same name. These naming clashes are solved in .NET by grouping classes logically in namespaces. So we can group different classes of a library into one or more namespaces. Whenever we use a library, we can specify to the compiler about the namespace we are referring.

Encapsulation
Encapsulation is all about hiding the data and ensuring its security. The data should not be accessible to any external entity unless the data is not that crucial.
   C# and VB.NET support various access specifiers to encapsulate the data and the functions. The specifiers allow us to define the levels of access for the data members. Every member that we declare in a class has to have to its access specifiers as a part of the declaration statement itself. Unlike C++ , both C# and VB.NET do not support access grouping.
C# Access Specifiers

Constructors
    Constructors are special member functions, which are used for initializing the class data members. In the earlier object oriented programming languages constructors were quite important since initialization of the data members was not allowed at the time of declaration. C# however allows us to have the member variables to be initialized along with declarations. Then why are constructors required? Well, the variables may not always be initialized to some constants but can also be initialized with the values specified by the user. There can also be certain kind of processing to be done while a class is instantiated. So a constructor happens to be quite important member function in the class as far as initialization is concerned.
 C# supports following types of constructors
• Default Constructors
• Parameterized constructors
• Private constructors
• Static constructors

Destructors
  C# also supports automatic memory cleanup by having a garbage collector element. So no more botheration for de-allocating memory from the heap and no more nightmares about dangling pointers. Then if there is a memory management mechanism why would we require destructors?

Static Members
   Let us consider a scenario wherein we have two different MS WORD windows opened with some documents opened. We select some text from one of the windows, copy it and try to paste it another window. Now we know that both these windows happen to be two separate entities. So lets imagine two objects of the same kind to have similar kind of interaction. Definitely we would a common memory are which both the objects would be able to access. This memory area also has to restricted to the objects of that class only. The key point over here is the common area available to the objects.
     In a second scenario, let us consider a requirement of generating ids automatically. Again, there has to be some variable, which would be common to all objects of that class and would keep on incrementing.


Properties
   Classes were proposed in object oriented programming paradigm for one of the reasons of having data security. As we know, the members of a structure in C happen to be public and can be accessed freely outside the structure. As a result, there is not any check as to what data is been inserted into the structure
members. Hence, in classes we have the “private” specifier by which we can avoid the direct access of the data members of the class. Then we lose the user friendliness of accessing a variable rather than calling a function.
   Properties happen to be a fantastic blend of both the things. A property constitutes of a private level member to store the data and accessor and mutator methods to interact with the variable. Now what is new in that? The beauty is that the property would be accessed by the user as a local variable but internally the
compiler will convert the access statements into appropriate function calls. So the user application always is under the impression that a variable is been accessed where as the validity of the data is been checked with the methods associated. The data stored in the variable is termed as value of the property.

Inheritence
It is one of the commonly used features in OOPS to avoid the code duplication. It implements code reutilization in class declaration. Let us take an example and discuss how the code reutilization is achieved with inheritence. Normally we create a singe class to represent an entity and its operations. Look at the
following example.


Class Employee
Public EmpId As Integer
Private Sal As Double = 0
Public Basic As Double
Public Allowance As Double
Public Deducions As Double
Public FirstName As String
Public LastName As String
Public Address As String
Public Pincode As String
Public Sub DisplayInfo()
Dim msg As String
msg = FirstName & " " & LastName & vbCrLf
msg = msg & Address & vbCrLf
msg = msg & "PIN – " & Pincode Msgbox(msg)
End Sub
Public ReadOnly Property Salary() As Double
Get
Return Sal
End Get
End Property
Public Sub ProcessSalary()
Sal = Basic + Allowance - Deductions
End Sub
End Class

Employee Class
class Employee
{
public int EmpId;
private double Sal = 0;
public double Basic;
public double Allowance;
public double Deducions;
public string FirstName;
public string LastName;
public string Address;
public string Pincode;
public void DisplayInfo()
{
string msg;
msg = FirstName + " " + LastName + vbCrLf;
msg = msg + Address + vbCrLf;
msg = msg + "PIN – " + Pincode;
MesssgeBox.Show(msg);
}
public double Salary
{
get
{
return Sal;
}
}
public void ProcessSalary()
{
Sal = Basic + Allowance – Deductions;
}
}
In the above example, employee class contains methods and properties defined in its structure. Employee object is an instance.
Class Customer
Public CustId As Integer
Public DebitBalance As Double
Public FirstName As String
Public LastName As String
Public Address As String
Public Pincode As String
Public Sub DisplayInfo()
Dim msg As String
msg = FirstName & " " & LastName & vbCrLf
msg = msg & Address & vbCrLf
msg = msg & "PIN – " & Pincode
End Sub
Public ReadOnly Property Debit() As Double
Get
Return DebitBalance
End Get
End Property
End Class

class Customer
{
public int CustId;
public double DebitBalance;
public string FirstName;
public string LastName;
public string Address;
public string Pincode;
public void DisplayInfo()
{
string msg;
msg = FirstName + " " + LastName ;
msg = msg + Address ;
msg = msg + "PIN – " ;
}
public double Debit()
{
get
{
return DebitBalance;
}
}
}
Customer class contains methods and properties defined in its structure. Customer object is an instance.
  In these two classes, you might have observed the person identification is same in both Employee and Customer class. it means firstname, lastname, address and pincode variable members and displayInfo method is same in both the classes.
  So this common information can be isolated and written in separate class and inherited into the respective employee and customer class. it is shown in the following example.

Base Class:-
Class Person
Public FirstName As String
Public LastName As String
Public Address As String
Public Pincode As String
Public Sub DisplayInfo()
Dim msg As String
msg = FirstName & " " & LastName & vbCrLf
msg = msg & Address & vbCrLf
msg = msg & "PIN – " & Pincode
Msgbox(msg)
End Sub
End Class


class Person
{
public string FirstName;
public string LastName;
public string Address;
public string Pincode;
public void DisplayInfo()
{
string msg;
msg = FirstName + " " + LastName;
msg = msg + Address ;
msg = msg + "PIN – " + Pincode;
MessageBox.Show(msg);
}
}

Derived Class:-
Class Customer
Inherits Person
Public CustId As Integer
Public DebitBalance As Double
Public ReadOnly Property Debit() As Double
Get
Return DebitBalance
End Get
End Property
End Class


class Customer:Person
{
public int CustId ;
public double DebitBalance;
public double Debit()
{
get
{
return DebitBalance;
}
}
}

Derived Class:-
Class Employee
Inherits Person
Public EmpId As Integer
Private Sal As Double = 0
Public Basic As Double
Public Allowance As Double
Public Deductions As Double
Public ReadOnly Property Salary() As Double
Get
Return Sal
End Get
End Property
Public Sub ProcessSalary()
Sal = Basic + Allowance - Deductions
End Sub
End Class

class Employee: Person
{
public int EmpId ;
private double Sal = 0;
public double Basic ;
public double Allowance;
public double Deductions;
public double Salary
{
get
{
return Sal;
}
}
public void ProcessSalary()
{
Sal = Basic + Allowance – Deductions;
}
}
   In the above mentioned example Person class holds the common data (Firstname, Lastname… etc) and method displayInfo(). It has been inherited in both employee and customer class. So these two achieves the same functionality of what we have seen before inheritance. By this point we conclude inheritance
implements reuse of the same code with multiple classes.
  One more advantage with inheritance is extensibility of the of the derived class code. It means the employee and customer class be extended by including its own methods and properties with the person (Inherited) class. Here the extended members in Employee class are EmpId, Allowance, ProcessSalary method and
Salary property. The same thing follows in customer class with CustId, DebitBalance and Debit property.
   You might have observed the keywords Base class and Derived class in the
above session. Let us see what it means.
Base class:- A class which contains common properties and methods that can shared with other classes by inheritance is called Base class.
Ex:- Person class
Derived class:- A class which inherits the base class is knows as Derived class.
Ex:- Employee class and Customer class.
Implementation:- A derived class can inherit only one base class. its shown in the above examples, ie., employee class inherits person class and customer class inherits person class.
  You can inherit the base class into derived class using Inherits keyword.
Ex:-
Class Employee
Inherits Person
:
:
End Class
class Employee:Person
{
:
:
}


Protected Keyword:- We have already seen the usage of Public and Private keyword.
  As we know, all the Public keyword declarations in the class will be accessed by the object users and the derived class (the class which inherits the base class). Private keyword declarations can be accessed only within the class (it means the class in which the declaration is done).
  You may think why this Protected keyword declaration is required.
  Its functionality is a hybrid of public and protected keyword. So, its very important in class inheritance, because in the situation where the data is to be communicated only between the base and derived classes irrespective of the external object user (means the end user) the protected keyword is used
Let us take an example and see how it will be used

Base Class:-
Class Person
Public FirstName As String
Public LastName As String
Public Address As String
Public Pincode As String
Protected DateOFBirth As DateTime
Public Sub DisplayInfo()
Dim msg As String
msg = FirstName & " " & LastName & vbCrLf
msg = msg & Address & vbCrLf
msg = msg & "PIN – " & Pincode
msg = msg & "Date of Birth : " & DateOFBirth.ToString
End Sub
End Class


class Person
{
public string FirstName ;
public string LastName ;
public string Address;
public string Pincode;
protected DateTime DateOFBirth ;
public void DisplayInfo()
{
string msg;
msg = FirstName + " " + LastName;
msg = msg + Address ;
msg = msg + "PIN – " + Pincode;
msg = msg + "Date of Birth : " + DateOFBirth.toString;
}
}
The Protected variable dateofbirth is accessed in the displayinfo method of the base class itself.

Derived Class:-
Class Employee
Inherits Person
Public EmpId As Integer
Private Sal As Double = 0
Public Basic As Double
Public Allowance As Double
Public Deducions As Double
Public ReadOnly Property Salary() As Double
Get
Return Sal
End Get
End Property
Public Sub ProcessSalary()
Sal = Basic + Allowance – Deductions
End Sub
Public ReadOnly Property Age() As Integer
Get
Dim personAge As Integer
personAge = Date.Now.Subtract(DateofBirth).Days
Return personAge
End Get
End Property
End Class


class Employee: Person
{
public int EmpId ;
private double Sal = 0;
public double Basic;
public double Allowance;
public double Deducions;
public double Salary
{
get
{
return Sal;
}
}
public void ProcessSalary()
{
Sal = Basic + Allowance – Deductions;
}
public int Age
{
get
{
int personage;
personAge = Date.Now.Subtract(DateofBirth).Days;
return personage;
}
}
}
As in the same way of base class the protected variable dateofbirth of the base class is accessed in the derived class. So the protected variable in the base class looks like a private variable for the derived class and cannot be accessed by its object users (means outside the class environment).

Instantiation of the Derived Class :- After declaration of the derived class we can create the object instance of the derived class and use it for the specific task. This is called Object Instantiation. With the instance of the derived class you can access all the public properties and methods of both the base and derived classes.
Let us take an employee class example.
Dim objEmployee1 As New Employee() 'Create an Instance of the
'Employee class
objEmployee1.EmpId = 100 'Derived Class member
objEmployee1.firstname = "Rama" 'Base Class member
objEmployee1.lastname = "S" 'Base Class member
objEmployee1.Address = "#8, Kalidasa road, Mysore"
'Base Class member
objEmployee1.pin = "570002" 'Base Class member
objEmployee1.Basic = 5000 'Derived Class member
objEmployee1.allowances = 4000 'Derived Class member
objEmployee1.Deductions = 1000 'Derived Class member
objEmployee1.ProcessSalary() 'Derived Class member
objEmployee1.DisplayInfo() 'Base Class member


Employee objEmployee1 = new Employee(); 'Create an Instance of the 'Employee class
objEmployee1.EmpId = 100; 'Derived Class member
objEmployee1.firstname = "Rama"; 'Base Class member
objEmployee1.lastname = "S"; 'Base Class member
objEmployee1.Address = "#8, Kalidasa road, Mysore";
'Base Class member
objEmployee1.pin = "570002"; 'Base Class member
objEmployee1.Basic = 5000; 'Derived Class member
objEmployee1.allowances = 4000; 'Derived Class member
objEmployee1.Deductions = 1000 ; 'Derived Class member
objEmployee1.ProcessSalary(); 'Derived Class member
objEmployee1.DisplayInfo(); 'Base Class member
  In the above code, object instance objEmployee of Employee class is created. And then all the public members of both base and derived class are accessed and manipulated.
System.Object:- This is the root class for all the objects in the .NET framework, from which all the other classes are derived. It contains some basic methods and properties, which can be accessed from all the object instances of the .NET framework.
Look into the code which calls system.object methods.
Dim Obj As New System.Object()
Obj.ToString()
Obj.GetHashCode()
Obj.GetType()
Dim objEmployee As New Employee()
objEmployee.ToString()
objEmployee.GetHashCode()
objEmployee.GetType()


System.Object Obj = new System.Object();
Obj.ToString();
Obj.GetHashCode();
Obj.GetType();
Employee objEmployee = New Employee();
objEmployee.ToString();
objEmployee.GetHashCode();
objEmployee.GetType();
   The above code shows some of the methods that can be accessed directly with the instance of the system.object ie., Obj and also the same methods can be accessed from objEmployee too. So, objEmployee is inherited from System.Object class.