Wednesday, 11 January 2012

Delegates and Events

Delegates and Events
Delegates:-
   The Delegate class is one of the most important classes to know how to use when programming .NET. Delegates are often described as the 'backbone of the event model' in VB.NET. In this we are going to introduce you to delegates (Sytem.Delegate class) and show you how powerful of an event mechanism
through delegates.
  Delegates are implemented using the delegate class found in the System namespace. A delegate is nothing more than a class that derives from System.MulticastDelegate. A delegate is defined as a data structure that refers to a static method or to a class instance and an instance method of that class. In other words, a delegate can be used like a type safe pointer. You can use a delegate to point to a method, much like a callback or the 'AddressOf' operator in VB.NET. Delegates are often used for asynchronous programming and are the ideal method for generically defining events.
    Before you get into the actual delegate class let us see some code which simulates the delegate functionality through simple class code for the sake of understanding. We have a simple class called 'VBDelegate' with two static methods named 'CallDelegate' and 'DisplayMessage' as shown below. When the CallDelegate method is called,(when the program is run) to display the message. Now normally, if we had a class called 'VBDelegate' with a method named 'DisplayMessage'

VB.NET
Public Class VBDelegate
'Static method to call displaymessage function
Public Shared Sub CallDelegate()
DisplayMessage("Some Text")
End Sub
'Static Function to display the message
Private Shared Function DisplayMessage(ByVal strTextOutput As String)
MsgBox(strTextOutput)
End Function
End Class

C#
Public Class CSDelegate
{
'Static method to call displaymessage function
Public static void CallDelegate()
{
DisplayMessage("Some Text")
}
'Static Function to display the message
Private static void DisplayMessage(String strTextOutput)
{
MessageBox.Show(strTextOutput)
}
}
  There is nothing wrong with this approach at all. In fact, it is probably more commonly used than delegates. However, it does not provide much in terms of flexibility or a dynamic event model. With delegates, you can pass a method along to something else, and let it execute the method instead. Perhaps you do not know which method you want to call until runtime, in which case, delegates also come in handy.
   Now we will implement the same functionality as before, using a actual delegate class of .NET.
Delegates in VB.NET are declared like:
Delegate [Function/Sub] methodname(arg1,arg2..argN)
  The declared delegate methodname will have the same method signature as the methods they want to be a delegate for. This example is calling a shared method..

VB.NET
Class VBDelegate
'Declaration of delegate variable with arguments
Delegate Function MyDelegate(ByVal strOutput As String)
'Function to call the delegates
Public Shared Sub CallDelegates()
'Declare variables of type Mydelegate points to the
'function MessageDisplay with AddressOf operator
Dim d1 As New MyDelegate(AddressOf MesssageDisplay)
Dim d2 As New MyDelegate(AddressOf MesssageDisplay)
'Pass the arguments to the function through delegates
d1("First Delegation ")
d2("Second Delegation ")
End Sub
'Function to display the message
Private Shared Function MesssageDisplay(ByVal strTextOutput As String)
MsgBox(strTextOutput)
End Function
End Class


C#
Class CSDelegate
{
'Declaration of delegate variable with arguments
delegate void MyDelegate(String strOutput);
'Function to call the delegates
Public static void CallDelegates()
{
'Declare variables of type Mydelegate points to the
'function MessageDisplay
MyDelegate d1 = New MyDelegate(MesssageDisplay);
MyDelegate d2 = New MyDelegate(MesssageDisplay);
'Pass the arguments to the function through delegates
d1("First Delegation ");
d2("Second Delegation ");
}
'Function to display the message
Private static void MesssageDisplay(String strTextOutput)
{
MessgeBox.Show(strTextOutput);
}
}
The Output to the display window is:
First Delegation in one message window
And
Second Delegation in the second message window
What has happened in the above code? Let's take a look
  First, we defined a delegate. Remember, when defining a delegate it is very similar to stating the signature of a method. We have said we want a delegate that can accept a string as an argument so basically, this delegate can work with any method that takes the same argument(s).
   In our CallDelagates method, we create two instances of our 'MyDelegate'. Then, we pass into MyDelegate's constructor the address of our 'DisplayMessage' method. This means that the method we pass into the delegate's constructor (in this case it's 'DisplayMessage' method) must have a method signature that
accepts a string object as an input argument, just like our delegate does. Now, you might be thinking, "why are we passing in the address of a method when we defined our delegate to accept a string object as it's input argument?" In the code above, we are telling the delegate which method to call, not which string we're
passing in. Carefully understand this concept.
  Then finally we have our 'DisplayMessage' method, which takes the string passed in by the delegate and tells it what string is to be displayed. The same approach is used while handling the events in the .NET. This topic is just to understand how delegates works in .NET.

Events:-
   Events are nothing but situations at which the message is sent to an object to signal the occurrence of the action. These actions can be caused by the user interaction or within the object itself.
  For example the class designer can create an event and raise the same through its methods and properties. These events will be captured by the object user and perform his/her required operation.
  Let us take a simple example of VB.NET Button class. Button is a class defined in System.Controls.FormsControls nameplace. The users create an instance of the Button class and select the onclick event related to the button object and write an action to be performed on click of the button.
   Actually this event is already defined in button class and will be raised when the user clicks the button. The following example shows how the event can be defined, raised in the class and used by the object user.
 Declaration:- The event member will be declared with Event keyword. Basically the event member should always be public. Because these are the members will be used by the external users.
'Declare a class which operates on the Employee collection database
'This class is used to find some summarised operation on the Employee
'collction database, which means finding the relavent employee ‘information, 'getting the
total no. of employees in the collection and ‘others - Its just 'an example to explain how
event works
Public Class EmployeeCollection
'Declare an event which will be raised after finding the data
'Keyword ‘Event’ is used the declare the events
Public Event FindResult(ByVal blnFound As Boolean)
'This method is to find the data from employee colletion database and 'raise the findresult
event to return the result
Public Sub FindData(ByVal Name As String)
'find the Employee with name and return the result as boolean, if
'the data is found then raise FindResult with True else with
'False
Dim found As Boolean
found = FineEmployee(Name)
If found Then
'Raise the event with parameter
RaiseEvent FindResult(True)
Else
'Raise the event with parameter
RaiseEvent FindResult(False)
End If
End Sub
End Class
Usage:- In order to access the events of the objects, the object should be declared with withevents clause. This is shown in the following example with form load event.
'Declare the object with WithEvents clause to create an instance
Dim WithEvents objEmpColl As EmployeeCollection = New EmployeeCollection()
Public Sub load()
'Find the Employee with name Rama in the Employee collection
objEmpColl.FindData("Rama")
End Sub
'The following event will be raised after the search operation
Private Sub objObject_FindResult(ByValue blnFound as Boolean) Handles
objObject.FindResult
If blnFound Then
MsgBox("The given Employee is Found in the collection")
Else
MsgBox("The given Employee is not Found")
End If
End Sub

Interfaces


    An interface is like an abstract class which allows the derived class to inherit more than one interfaces into it.
   We have already seen an abstract class can have methods with or without implementation. But an interface can only have members without implementation. So it provides only structure of the objects like abstract class.
   To implement an interface in VB.NET, we use the keyword Implements and we must provide implementations for all the methods of the interface we implements.
Defining an Interface:- Interfaces are declared with the following structure
Public Interface <Name of the interface>
:
<decleration of memebrs of the interface, means methods and properties
structure>
:
End Interface
Let us take up a example and see how the declaration been done
Interface IShape
Sub Draw(ByVal coord() As ArrayList)
End Interface
interface IShape
{
void Draw(ArrayList coord);
}
Implementation of Interface:- Interfaces are implemented using Implements keyword. All the members of the interface are implemented with Implements keyword.
“To implement a interface, we must implement all the methods and properties defined by the
interface”
If more than one interface is to be implemented, then interfaces names should separated by commas with the implements keyword while defining a class.
Lets us take an example of implementation:-
Public Class Drawing
Implements Ishape
Public Sub Draw(ByVal parCoord() As ArrayList) Console.Write("Draw a Circle")
End Sub
End Class


Public Class Drawing: Ishape
{
Public void Draw (ArrayList parCoord)
{
Console.Write("Draw a Circle");
}
}
In the example, we are implementing Isahpe interface, which contains Draw method into the Drawing Class.
Difference between Abstract class and Interfaces

When to use the interfaces in programming?
Solution:- The situation at which we need to implement the functionalities of two or more objects into one derived object. So it makes the derived object to refer to the interface methods and properties for syntax verification.

Abstract Classes (Virtual Class)


  So far, we have seen how to inherit the class, how to overload and override methods. In the examples shown in inheritance topic, parent class has been useful in both inheritance and create an instance also.
   Actually in some situation the classes are required only for inheritance, such type of classes are called Abstract classes. This concept is very useful when creating a framework for the applications where there will not be any implementation for the methods and properties in the abstract class. It just defines the structure.
  Abstract classes are declared using MustInherit and MustOverride keyword.
Syntax:-
Public MustInherit Class AbstractBaseClass
Public MustOverride Sub DoSomething()
Public MustOverride Sub DoOtherStuff()
End Class


public abstract class AbstractBaseClass
{
public abstract void DoSomething();
public abstract void DoOtherStuff();
}
MustInherit keyword is used with the class name, where as MustOverride keyword is used with the members of the class.
Implementaion:-
Public Class DerivedClass
Inherits AbstractBaseClass
Public Overrides Sub DoSomething()
MsgBox("This method is overrides the Base class DoSomething to implement the method functionality”)
End Sub
Public Overrides Sub DoOtherStuff()
MsgBox(“This method is overrides the Base class DoOtherStuff to implement the method functionality”)
End Sub
End Class


public class DerivedClass : AbstractBaseClass
{
public Override void DoSomething()
{
MessagegBox.Show("This method is overrides the Base class DoSomething to implement the method functionality”);
}
public Override void DoOtherStuff()
{
MessaggeBox.Show(“This method is overrides the Base class DoOtherStuff to implement the method functionality”);
}
}
  MustInherit forces the classes to be inherited from the derived class and write an implementation code for the methods and properties in the derived class before using it.
  As in the above example, any class that inherits AbstractBaseClass must implement the Dosomething and DoOtherStuff methods.
We cannot create an instance of the AbstractBaseClass as shown below.
Dim obj as New AbstractBaseClass()
‘Error in Decleration
AbstractBaseClass obj = new AbstractBaseClass()
‘Error in Decleration


Restricting Inheritence
If we want to prevent a class being used as a Base class we can use NotInheritable keyword with the class declaration.
Public NotInheritable Class NormalClass
'Decleration of Class members
End Class
public sealed class NormalClass
{
'Decleration of Class members
}
For example when we want an employee class need not to be used as a Base class, we can declare the employee class structure with NotInheritable keyword.
So that it can be used only for instantiation.

VB.NET
Class NotInheritable 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 Shadows Sub DisplayInfo()
Dim msg As String
msg = MyBase.DisplayInfo("")
msg = msg & "ID : " & EmpId.ToString & vbCrLf
msg = msg & "Basic : " & Basic.ToString & vbCrLf
msg = msg & "Allowances : " & Allowance.ToString & vbCrLf
msg = msg & "Deductions : " & Deductions.ToString & vbCrLf
msg = msg & "Net Salary : " & Basic.ToString & vbCrLf
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
Following decleration is not posssible, .NET generates error!!!!
Public Class Staff
Inherits Employee
End Class


C#
class sealed Employee: Person
{
public int EmpId ;
private double Sal = 0;
public double Basic;
public double Allowance;
public double Deductions;
public new void DisplayInfo
{
string msg;
msg = Base.DisplayInfo("");
msg = msg + "ID : " + EmpId.ToString;
msg = msg + "Basic : " + Basic.ToString;
msg = msg + "Allowances : " + Allowance.ToString;
msg = msg + "Deductions : " + Deductions.ToString;
msg = msg + "Net Salary : " + Basic.ToString;
MessageBox.Show(msg);
}
public double Salary
{
get
{
return Sal;
}
}
public void ProcessSalary()
{
Sal = Basic + Allowance – Deductions;
}
}
Following decleration is not posssible, .NET generates error!!!!
Public Class Staff: Employee
{
----
}

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.


Polymorphism


The word “polymorphism” means “different forms”. Applied in object-oriented paradigm it means the ability of an entity to exhibit different forms at runtime. However, why would such a kind of feature be required? One major reason to have this is to eliminate the type inspection. As we can see in the earlier case study that we discussed there would also be a type inspection checking at the client application level where in the employee entities would be used. So just as in every functionality, we had checked for the type of employee we will also have to check in the main function about the type of employee we are handling. With polymorphism, we can have this level of type inspection also being eradicated totally.

Mapping the procedural approach to an object oriented scenario
 
How does .NET support object oriented programming?
   As we have discussed in the earlier sections .NET happens a to be a “complete framework”. The basic approach adopted by the framework is object-oriented and the framework would support only object-oriented code. So no more C and COBOL applications! Although C++ and OO-COBOL would work perfectly fine.
  Since the framework is inherently object-oriented everything i.e. every data type in the framework will be a class. Unlike C++, even the primitive data types will be given by the framework as a set of classes.
    The framework also provides us with a rich set of classes which can be used by instantiating them or writing new classes by deriving from the framework classes. The framework does have a systematic organization of classes wherein the Object class from the System namespace (we will discuss namespaces in details later) tops the chart. All the other classes are derived from the Object class.

Component Oriented Programming
   However, is it really enough just to have an object oriented approach? Well, now with the increasing influence of the web and code reusability getting extended across the language barriers its very much essential to even extend “Object Oriented approach “ itself.
   We need to extend the definition of the “class” which happens to be the basic element of object oriented programming. We know that the class serves as an abstraction or simulation of a real life entity. However, in order to have a total encapsulation the internals of the class has to be totally hidden. Secondly, the class should be instantiable across various programming languages to have a more range of reusability. The class should ideally support properties (will be discussed a little later) to offer more user friendliness and overcoming the incompatibilities.
Therefore, a class must have the following extra abilities in addition to what it serves in object-oriented scenario:
• Encapsulated data and implementations
• Properties
• Language Interoperable
  We can term instance of such a class as a “component”. VB.NET and CSharp happen to be component- oriented languages in a way that every class created in any of these languages when instantiated results in a component.

Inheritance


What is common between a father and a son? At least one thing would be common – their assets!
  In real life, inheritance allows us to reuse things that belong to a particular entity. Also, in object oriented world a class can inherit the properties and functionalities defined in some another class so that they can be reused. Then we have to be a bit careful in designing these classes because reusability cannot be done unless
the classes are of the same type. So the class which would be reusing the functionalities of the other class in object oriented terms we would say that the class is “deriving” from the former class and is termed as the derived class. The class that is being “derived from” is termed as the base class. Inheritance directly results in the following benefits: --
Reusability: -- Inheritance results in functionalities defined in one class being reused in the derived classes. So the efforts of rewriting the same functionality for every derived class is being saved. This definitely saves a lot of development time.
Enhancement and Specification: -- Due to the characteristic of inheritance, we can club the common functionalities in the base class and have the specific functionalities in the derived class. This feature can be used to have a functionality defined in the base class to be further modified for betterment or specification by the derived class. This mechanism of redefining the functionality of the base class in the derived class is termed as “overriding”
Avoiding type inspection:-- In the case study that we discussed to understand procedural approach we had a strict type inspection routine at the library end wherein in every function in the library we had to check for the type of the employee for whom the work has to be done. With inheritance, we would have a common base class called as “Employee” which would have all the common functionalities defined where as the specific routines do be done for various types of employees would go in the respective derived classes. So there would be class defined for every type of employee and the class would all the specifications for that type of employee and would be derived from the base class Employee to inherit the common functionalities. Therefore, in the functions now we wont have to check for the type of employee every time because every
employee type has its own specific routines defined within it.

Encapsulation


  Many a times when we use certain tools, we hardly pay attention to the details about the functionality of the tool. We hardly pay attention to the various other units, which make up the tool. This behavior to ignore unwanted details of an entity is termed as abstraction.
  Now if the details are unwanted why show them to the user? Therefore, the creator might attempt to hide these unwanted details. This behavior is termed as encapsulation. So we can say that encapsulation is an implementation of abstraction. Encapsulation directly leads to two main advantages:
Data Hiding: -- The user of the class does not come to know about the internals of the class. Hence, the user never comes to know about the exact data members in the class. The user interacts with the data members only through the various member functions provided by the class.
Data Security: - Since the data, members are not directly available to the user directly but are available only through the member functions a validity check can always be imposed to ensure that only valid data is been inserted into the class.
   So a Date class, which contains individual data members for storing date, month and year, will have it ensured the month is never 13 or the date is never exceeding 31.