Monday, 12 May 2014

Beginner’s tutorial for ASP.NET programming – Part 2

Creating the Database Table
Here we will create a table called ‘LoginTable’ in our SQL Server. Please have a look at Figure-22 for the design structure of the table. This table contains two columns ‘Name’ and ‘Password’.
Figure-22: Structure of the ‘LoginTable’
Figure-22: Structure of the ‘LoginTable’
Now we will add the following data in this table
Figure-23: Data in the ‘LoginTable’
Figure-23: Data in the ‘LoginTable’
So the table at the back end is also prepared for our Tutorial.
Connecting the Database table from our web application
In the next step we will demonstrate how to connect the database table in windows authentication mode from our web application. There are several methods for this but here we will show the method of declaring a key ‘ConnectionString’ and its value in Web.config file. Add the following line under the <appsettings> section of web config:
<appSettings>
<add key=” ConnectionString” value=”Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Practice” />
</appSettings>
Here as our SQL Server belongs to the same machine we do not mention any server name in the ‘value’.
Integrated Security=SSPI refers windows authentication to connect to the database.
Initial Catalog specifies the Database name in which our table belongs. In our example we create the ‘LoginTable’ under ‘Practice’ database. You may create the table under different database . In that case you specify the database name in place of ‘Practice’.
Creating the code behind page for Login.aspx to make the application ready
The default method for implementing server side code in Visual Studio is to use code-behind pages. When we use code-behind pages, the programming logic is in a separate file than the visual elements of the page.
To go to the page behind page press F7 in the Design view of ‘Login.aspx’ page or from the solution explorer click ‘Login.aspx.cs’ . At the top of this page you will find the default namespaces declared. Most of the general purpose .Net base classes are in a namespace called ‘system’. Now to connect with the SQL Server please add another namespace ‘System.Data.SqlClient’ as shown in the Figure-24:
Figure-24: Add the System.Data.SqlClient namespace in the code behind page
Figure-24: Add the System.Data.SqlClient namespace in the code behind page
You can now find a function Page_Load() declared in the code behind page. This is a page event which runs every time the page is requested. Now it is not only the one page event. When an ASP.NET page is requested, there are a series of page events that occur. These events always occur in the same order , which is referred to as the page event life cycle. Let’s discuss on it in brief.
The page event life cycle consists of the following page events, which occur in the following order:
Page request: The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled or whether a cached version of the page can be sent in response without running the page.
Start:In the start step, page properties such as Request and Response are set.
Page initialization:This page event initializes the page by creating and initializing the web server controls on the page.
Load:This event runs every time the page is requested.
Validation:During validation, the Validate method of all validator controls is called, which sets the ‘IsValid’ property of individual validator controls and of the page.
Postback event handling:If the request is a postback, any event handlers are called.
Rendering: During the rendering phase, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream of the page’s Response property.
Unload:Unload is called after the page has been fully rendered, sent to the client, and is ready to be discarded.
Now let’s back in our example. Here the user will enter the ’Name’ and ‘Password’ in our Login.aspx page and we will search our ‘LoginTable’ with those credentials to find any existing entry. If such entry exists then user will be redirected to the ‘Welcome.aspx’ page.
So at first we will create a boolean function ‘SearchTable()’ which creates and opens a SQL connection. After that we will search the ‘LoginTable’ with the proper query (with the entered ‘Name’ and ‘Password’) and if any match found then the function will return true, otherwise it returns false. Please find the attached snapshot (Figure-25) to get the code.
Figure-25: Details of the function ‘SearchTable()’
Figure-25: Details of the function ‘SearchTable()’
The code shown here is self explanatory but let’s again clarify two terms:
DataSet: These are complex objects that allow you to store multiple DataTables of data from a data source. DataSet objects are similar to a virtual database that is inside a web application.
DataAdapter: This object serves as a link between a DataSet object and a data source that can be used for retrieving and saving data. The SqlDataAdapter class is specific to a SQL Server version 7.0 or later database.
Now we will call this ‘SearchTable()’ function when the user click’s the ‘Submit’ button from Login.aspx page. Just go to the Design view of this page and click on the ‘Submit’ button. This will add the button click event at the code behind page like this:
Figure-26: Click event function added on the code behind page
Figure-26: Click event function added on the code behind page
Now add these lines within this function to complete the application.
Figure-27: Call the ‘SearchTable’ function and set the proper output
Figure-27: Call the ‘SearchTable’ function and set the proper output
Now our web application is ready for testing.
Testing the Web Application
Now set the start page ‘Login.aspx’ by right clicking on the project in solution explorer and press F5 to run the application from localhost. If you are working in windows XP please install IIS from the ‘Additional Windows Components’ of Windows XP CD before running the application.
Here we can have three test sceanarios:
Scenario 1:
User does not enter anything in the text boxes and press the ‘Submit’ button. In this case the ‘Required field Validators ‘ will show ‘Required’ messages. Please have a look at the two figures below to understand the scenario:
Figure-28: Click on ‘Submit’ without entering values in the text boxes
Figure-28: Click on ‘Submit’ without entering values in the text boxes
Figure-29: Desired output for scenario 1
Figure-29: Desired output for scenario 1
Scenario 2:
User will enter a valid ‘Name’ and ‘Password’ and click’s on ‘Submit’. User will be redirected to ‘Welcome.aspx’ page. Figure-30 and 31 will make yourself clear about this scenario:
Figure-30: User enters a correct entry
Figure-30: User enters a correct entry
Figure-31: Desired output for correct entry
Figure-31: Desired output for correct entry
Scenario-3
User enters a wrong ‘Name’ or ‘Password’ or both and then he/she will be prompted by an error message at the bottom of ‘Login.aspx’ page. Here are the screenshot of the test case and desired output.
Figure-32: User enters  a wrong ‘Name’
Figure-32: User enters a wrong ‘Name’
Figure-33: Desired output for scenario-3
Figure-33: Desired output for scenario-3

So our application is working fine for the entire test scenarios.


Please leave your comments and feedback.

ASP.NET programming tutorial for beginner – Part-I

Introduction
The term .Net gives us a feeling that it is something to do only with the Internet or network related  applications. Though .Net provides strong environment for creating such applications, it is also possible to create many other types of applications (Windows form based applications, Console applications, Windows custom controls etc.)
.Net is Microsoft’s development model in which software becomes platform and device independent and data becomes available over the Internet. The .Net framework is the heart of .Net. Central to the .Net framework is its runtime execution environment known as the Common Language Runtime (CLR) and the code running under the control of the CLR is often termed as Managed Code.
In this tutorial we will show how to create a dynamic data driven web application in .Net environment and we also focus on understanding basic ASP.Net components for web application.
Problem Statement for this tutorial
We will create a web application which asks user to provide user id and password (both are required fields).We will store some user ids and corresponding passwords in database table. If a user id and password matches with the database entry at the back end then the user will be redirected to Welcome page, otherwise he /she will be prompted a Invalid Login message.
Approach
We will divide this into two parts. In first part we discuss how to create and design the web pages in VS 2008, how to add web controls in the pages, available validation controls and their features etc.
In second part we show the procedure to connect the web application with SQL Server and discuss about the ADO.Net controls and finally compile and run the application to verify its correctness.
Requirements
• Windows XP Professional with Service Pack 2/Windows Vista
• Internet Explorer 6 or later/Any Web Browser
• Visual Studio 2005/2008 Professional
• SQL Server 2005/2008 Developer Edition
• IIS (Internet Information Service) version 5.0 or later
Here we have set up the example with Visual Studio 2008 and SQL Server 2005 environment. But you can also proceed with VS 2005 version.
Installation
Both Visual Studio and SQL Server are not free. You need to purchase it from Microsoft but you can download the trial versions of both of these software from Microsoft. Here are the links:
http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=83c3a1ec-ed72-4a79-8961-25635db0192b (Visual Studio 2008 Professional Edition Trial Version)
http://www.microsoft.com/sqlserver/2005/en/us/trial-software.aspx (Download the developer version of SQL Server 2005)
If you are working in Windows XP then you need to install IIS in your machine. Go to ‘Start->Settings->Control Panel’. Click On ‘Add/Remove Programs’ and then select ‘Add/Remove Windows Components’. Now from the Windows Component Wizard select Internet Information Services and click ‘next’ to proceed. You need to insert Windows XP Professional CD to complete the set up.
IIS 7.0 is included with Windows Vista.
Creating the Web Application
Once you launch the VS 2008 you will be presented with a window similar to the screen shot below:
Figure-1: Start Page of VS 2008
Figure-1: Start Page of VS 2008
The Start Page is the first page you see whenever you launch Visual Studio 2008 and this page guides you as you start projects, as well as search for help or resources. From the screen shot you can see the Recent Projects box at the left side of the page. This box contains the latest projects on which we have worked. From this box you can also create a new project or open an existing project that is not listed. The Getting Started box allows you to create new projects from existing code , create new web sites, pull up the MSDN help application. If you close the Start page from Document Window you can reactivate the Start Page by selecting View->Other Windows->Start Page option.
Now close the Start Page and from the Visual Studio Menu go to File->New->Web Site like Figure-2(below)
Figure-2: Create New Web site from the Menu
Figure-2: Create New Web site from the Menu
Now you will see another window appears to select the template. Select the ASP.Net Web Site template and name it as “TutorialExample” like the screenshot below. Set the Language at the right side as Visual C# (it is the language that will be used at the code behind page which will be discussed later). You may also set it as Visual Basic but here we have used C# to show the example.
Figure-3: Create the “TutorialExample” web site
Now the Default.aspx page will be opened like the screenshot below. The Solution Explorer (at the right side) which provides an organized view of the project contains one folder (App_Data) and two files.
Figure-4: Default page and the Solution Explorer
Figure-4: Default page and the Solution Explorer
The App_Data folder is the default directory for database but here we will not use this folder as we will use separate SQL Server database. Application and directory level settings are stored in Web.Config file. Each Web Application has at least one Web.config file.
Now select the Default.aspx file in the Solution explorer and press F2 to rename it as Login.aspx (Screen shot below).
Figure-5: Rename Default.aspx as Login.aspx
The document window is where you create the ASP.NET pages. This section of the IDE enables you to create ASP.NET pages either by dragging and dropping elements onto a design surface or by directly coding them. Visual Studio 2008 offers three views of a page: Design, Split and Source view but Visual Studio 2005 offers only two views: Design and Source. Figure-6 shows the document window in VS 2008 with Split View.
Figure-6: Split View of Login.aspx page in the document window
Figure-6: Split View of Login.aspx page in the document window
Now we will add server controls in our Login page. But before doing that we will briefly discuss what is a server control. ASP.NET server controls are components that run on the server and encapsulate UI and other related functionality . Server controls include Buttons, Text Boxes, Drop Down Lists etc. The following is an example of Button server control:
Server controls have a runat=”server” attribute. This means that the logic in the control runs on the server and not on the user’s browser. Server controls are different from HTML controls in that they run only on the client’s browser and have no action on the server. Another feature of server controls is that the view state, the settings and the user input of the control are automatically saved when the page is sent back and forth between the client and the server. Traditional HTML controls are stateless and revert to their default setting when the page is returned from the server to client.
Now let’s add web server controls within a table in our Login page. Place the following code in the source view to create a table first. Please look at Figure-7 to add a table.
Figure-7: Add a 3x3 table in the Login Page
Figure-7: Add a 3x3 table in the Login Page
Now if you go to the Design view you will find a table like Figure-8.
Figure-8: Table in the Design view
Figure-8: Table in the Design view
You can also change the style of this table (like set border, change border color ,width etc.) from the Design view. As an example we will just set a border for this table. Select the table in the design view and press ‘F4’. It will open the Properties Window which controls the properties of any item that is a part of your application. Now change the border type as shown in Figure-9:
Figure-9: Change the Border type of the table
Figure-9: Change the Border type of the table
You may also change the other properties from this window as experiment.
Now we will add controls within this table. At the right bottom of the page you can find an icon called ‘ToolBox’ which basically allows you to use a drag and drop operation on the controls in this application. When you click on it , you can find the available tools grouped by category. Please have a look on Figure-10 for details.
Figure-10: Tools grouped by Category in the Toolbox
Figure-10: Tools grouped by Category in the Toolbox
Now expand the standard category which consists of Web Server Controls and drag a ‘TextBox’ control from it and drop it in the second column of the first row like Figure-11.
Figure-11: A TextBox is added in the second column of first row
Figure-11: A TextBox is added in the second column of first row
Now add another TextBox in the column below and a Button at the last like Figure-12.
Figure-12: Text Box and Button Controls are added
Figure-12: Text Box and Button Controls are added
Then write ‘Name’ and ‘Password’ like Figure-13: in the Table
Figure-13: Name and Password added
Figure-13: Name and Password added
Now Select the button control and press F4 to view the properties window. In properties change the ‘Text’ property from ‘Button’ to ‘Submit’ (shown in Figure-14)
Figure-14: Change the Text property of the Button control
Figure-14: Change the Text property of the Button control
After changing this property the design view of Login page will be like Figure-15
Figure-15: ‘Submit’ button  Added
Figure-15: ‘Submit’ button Added
At last we will add validation controls for two text boxes. The ASP.Net page framework includes different types of validation controls . Here we are adding small description of different types of validation controls:
•CompareValidator: Compares an input control to another input control
•CustomValidator: Allows you to write your own code to create the validation expression.
•RangeValidator: This can verify that the user input is between two values.
•RegularExpressionValidator: Verifies that the entry matches a pattern that has been specified by a regular expression.
•RequiredFieldValidator: Checks whether a value has been entered into a control or not.
•ValidationSummary: Displays a summary of all of the validation errors for all of the validation controls on the page.
In our application user need to provide both ‘Name’ and ‘Password’ and these are required fields. So we will add two RequiredFieldValidator for the two TextBoxes. Now drag two ‘RequiredFieldValidator’ from the ‘Validation’ category of ToolBox and place them at the last column of the first two rows of the table.
Here is the screenshot:
Figure-16: Two RequiredFieldValidators are added
Figure-16: Two RequiredFieldValidators are added
Now select the two RequiredFieldValidators one by one and set the ‘ControlToValidate’ property as ‘TextBox1’ and ‘TextBox2’ respectively . Set the ‘ErrorMessage’ property of both of them as ‘Required’. Please look at the screenshot below for details:
Figure-17: Change the properties of the RequiredFieldValidator1 (same for the second)
Figure-17: Change the properties of the RequiredFieldValidator1 (same for the second)
As a result of this if an user press the ‘Submit’ button keeping the TextBox1 or TextBox2 blank, then he/she will get a ‘Required’ message beside the appropriate TextBox .
At last we will add a asp:label control below the table. If a user enters a wrong ‘Name’ or ‘Password’ then this control will show the proper error message. From the properties window set the ‘ForeColor’
‘Red’ and leave ‘Text’ blank as shown in Figure-18.
Figure-18: Change the ‘ForeColor’ and ‘Text’ properties of ’ Label1’
Figure-18: Change the ‘ForeColor’ and ‘Text’ properties of ’ Label1’
So our Login.aspx page is ready. Now we will add another web page called ‘Welcome.aspx’ into our project. This page will contain just one one ‘label’ control which will show a welcome message after successful login.
To add another web page in our project just right click on the project in the Solution Explorer and select ‘Add New Item’ (Shown in Figure-19)
Figure-19: Select ‘Add New Item’ to add another page

Figure-19: Select ‘Add New Item’ to add another page
From the appeared templates select ‘Web Form’ and Name it as ‘Welcome.aspx’ (screenshot below)

Figure-20: Add ‘Welcome.aspx’ page in the project

Figure-20: Add ‘Welcome.aspx’ page in the project

Now in the design view drag and drop a ‘Label’ control from the toolbox and change the properties like the attached snapshot.


Figure-21: Add welcome label in ‘Welcome.aspx’ page



If You Fine this tutorial helpful pleaz like...

Introduction to Object Oriented Programming Concepts (OOPS) in C#.net

Introduction to Object Oriented Programming Concepts (OOPS) in C#.net

OOPS Concepts

Class:

 It is a collection of objects.

Object:

It is a real time entity.
An object can be considered a "thing" that can perform a set of related activities. The set of activities that the object performs defines the object's behavior. For example, the hand can grip something or aStudent (object) can give the name or address. In pure OOP terms an object is an instance of a class


The above template describe about object Student
Class is composed of three things name, attributes, and operations

public class student
{
}
student objstudent=new student ();

According to the above sample we can say that Student object, named objstudent, has created out of the student class.

In real world you will often find many individual objects all of the same kind. As an example, there may be thousands of other bicycles in existence, all of the same make and model. Each bicycle has built from the same blueprint. In object-oriented terms, we say that the bicycle is an instance of the class of objects known as bicycles. In the software world, though you may not have realized it, you have already used classes. For example, the Textbox control, you always used, is made out of the Textbox class, which defines its appearance and capabilities. Each time you drag a Textbox control, you are actually creating a new instance of the Textbox class.

Encapsulation:

Encapsulation is a process of binding the data members and member functions into a single unit.

Example for encapsulation is class. A class can contain data structures and methods.
Consider the following class

public class Aperture
{
public Aperture ()
{
}
protected double height;
protected double width;
protected double thickness;
public double get volume()
{
Double volume=height * width * thickness;
if (volume<0)
return 0;
return volume;
}
}

In this example we encapsulate some data such as height, width, thickness and method Get Volume. Other methods or objects can interact with this object through methods that have public access modifier

Abstraction:

Abstraction is a process of hiding the implementation details and displaying the essential features.

Example1: A Laptop consists of many things such as processor, motherboard, RAM, keyboard, LCD screen, wireless antenna, web camera, usb ports, battery, speakers etc. To use it, you don't need to know how internally LCD screens, keyboard, web camera, battery, wireless antenna, speaker’s works.  You just need to know how to operate the laptop by switching it on. Think about if you would have to call to the engineer who knows all internal details of the laptop before operating it. This would have highly expensive as well as not easy to use everywhere by everyone.

So here the Laptop is an object that is designed to hide its complexity.
How to abstract: - By using Access Specifiers

.Net has five access Specifiers

Public -- Accessible outside the class through object reference.

Private -- Accessible inside the class only through member functions.

Protected -- Just like private but Accessible in derived classes also through member 
functions.

Internal -- Visible inside the assembly. Accessible through objects.

Protected Internal -- Visible inside the assembly through objects and in derived classes outside the assembly through member functions.

Let’s try to understand by a practical example:-


public class Class1
    {
        int  i;                                         //No Access specifier means private
        public  int j;                                        // Public
        protected int k;                             //Protected data
        internal int m;                        // Internal means visible inside assembly
        protected internal int n;                   //inside assembly as well as to derived classes outside assembly
        static int x;                                 // This is also private
        public static int y;                       //Static means shared across objects
        [DllImport("MyDll.dll")]
        public static extern int MyFoo();       //extern means declared in this assembly defined in some other assembly
        public void myFoo2()
        {
            //Within a class if you create an object of same class then you can access all data members through object reference even private data too
            Class1 obj = new Class1();
            obj.i =10;   //Error can’t access private data through object.But here it is accessible.:)
            obj.j =10;
            obj.k=10;
            obj.m=10;
            obj.n=10;
       //     obj.s =10;  //Errror Static data can be accessed by class names only
            Class1.x = 10;
         //   obj.y = 10; //Errror Static data can be accessed by class names only
            Class1.y = 10;
        }
    }

Now lets try to copy the same code inside Main method and try to compile
[STAThread]
        static void Main()
        {
           //Access specifiers comes into picture only when you create object of class outside the class
            Class1 obj = new Class1();
       //     obj.i =10; //Error can’t access private data through object.
            obj.j =10;
      //      obj.k=10;     //Error can’t access protected data through object.
            obj.m=10;
            obj.n=10;
       //     obj.s =10;  //Errror Static data can be accessed by class names only
            Class1.x = 10;  //Error can’t access private data outside class
         //   obj.y = 10; //Errror Static data can be accessed by class names only
            Class1.y = 10;
        }
What if Main is inside another assembly
[STAThread]
        static void Main()
        {
           //Access specifiers comes into picture only when you create object of class outside the class
            Class1 obj = new Class1();
       //     obj.i =10; //Error can’t access private data through object.
            obj.j =10;
      //      obj.k=10;     //Error can’t access protected data through object.
     //     obj.m=10; // Error can’t access internal data outside assembly
    //      obj.n=10; // Error can’t access internal data outside assembly

       //     obj.s =10;  //Errror Static data can be accessed by class names only
            Class1.x = 10;  //Error can’t access private data outside class
         //   obj.y = 10; //Errror Static data can be accessed by class names only
            Class1.y = 10;
        }
In object-oriented software, complexity is managed by using abstraction.
Abstraction is a process that involves identifying the critical behavior of an object and eliminating irrelevant and complex details.

Inheritance:

Inheritance is a process of deriving the new class from already existing class
C# is a complete object oriented programming language. Inheritance is one of the primary concepts of object-oriented programming. It allows you to reuse existing code. Through effective use of inheritance, you can save lot of time in your programming and also reduce errors, which in turn will increase the quality of work and productivity. A simple example to understand inheritance in C#.


Using System;
Public class BaseClass
{
    Public BaseClass ()
    {
        Console.WriteLine ("Base Class Constructor executed");
    }
                                 
    Public void Write ()
    {
        Console.WriteLine ("Write method in Base Class executed");
    }
}
                                 
Public class ChildClassBaseClass
{
                                 
    Public ChildClass ()
    {
        Console.WriteLine("Child Class Constructor executed");
    }
   
    Public static void Main ()
    {
        ChildClass CC = new ChildClass ();
        CC.Write ();
    }
}

In the Main () method in ChildClass we create an instance of childclass. Then we call the write () method. If you observe the ChildClass does not have a write() method in it. This write () method has been inherited from the parent BaseClass.

The output of the above program is

Output:
  Base Class Constructor executed
  Child Class Constructor executed
  Write method in Base Class executed

this output proves that when we create an instance of a child class, the base class constructor will automatically be called before the child class constructor. So in general Base classes are automatically instantiated before derived classes.

In C# the syntax for specifying BaseClass and ChildClass relationship is shown below. The base class is specified by adding a colon, ":", after the derived class identifier and then specifying the base class name.

Syntax:  class ChildClassNameBaseClass
              {
                   //Body
              }

C# supports single class inheritance only. What this means is, your class can inherit from only one base class at a time. In the code snippet below, class C is trying to inherit from Class A and B at the same time. This is not allowed in C#. This will lead to a compile time 
error: Class 'C' cannot have multiple base classes: 'A' and 'B'.

public class A
{
}
public class B
{
}
public class C : A, B
{
}

In C# Multi-Level inheritance is possible. Code snippet below demonstrates mlti-level inheritance. Class B is derived from Class A. Class C is derived from Class B. So class C, will have access to all members present in both Class A and Class B. As a result of multi-level inheritance Class has access to A_Method(),B_Method() and C_Method().

Note: Classes can inherit from multiple interfaces at the same time. Interview Question: How can you implement multiple inheritance in C#? Ans : Using Interfaces. We will talk about interfaces in our later article.

Using System;
Public class A
{
    Public void A_Method ()
    {
        Console.WriteLine ("Class A Method Called");
    }
}
Public class BA
{
    Public void B_Method ()
    {
        Console.WriteLine ("Class A Method Called");
    }
}
Public class CB
{
    Public void C_Method ()
    {
        Console.WriteLine ("Class A Method Called");
    }
                   
    Public static void Main ()
    {
        C C1 = new ();
        C1.A_Method ();
        C1.B_Method ();
        C1.C_Method ();
    }
}
When you derive a class from a base class, the derived class will inherit all members of the base class except constructors. In the code snippet below class B will inherit both M1 and M2 from Class A, but you cannot access M2 because of the private access modifier. Class members declared with a private access modifier can be accessed only with in the class. We will talk about access modifiers in our later article.Common Interview Question: Are private class members inherited to the derived class?

Ans: Yes, the private members are also inherited in the derived class but we will not be able to access them. Trying to access a private base class member in the derived class will report a compile time error.

Using System;
Public class A
{
Public void M1 ()
{
}
Private void M2 ()
{
}
}

Public class BA
{
Public static void Main ()
{
B B1 = new B ();
B1.M1 ();
//Error, Cannot access private member M2
//B1.M2 ();
}
}
Method Hiding and Inheritance We will look at an example of how to hide a method in C#. The Parent class has a write () method which is available to the child class. In the child class I have created a new write () method. So, now if I create an instance of child class and call the write () method, the child class write () method will be called. The child class is hiding the base class write () method. This is called method hiding.

If we want to call the parent class write () method, we would have to type cast the child object to Parent type and then call the write () method as shown in the code snippet below.


Using System;
Public class Parent
{
    Public void Write ()
    {
        Console.WriteLine ("Parent Class write method");
    }
}
Public class ChildParent
{
    Public new void Write ()
    {
        Console.WriteLine ("Child Class write method");
    }
   
    Public static void Main ()
    {
        Child C1 = new Child ();
        C1.Write ();
        //Type caste C1 to be of type Parent and call Write () method
        ((Parent) C1).Write ();
    }
}

Polymorphism:

When a message can be processed in different ways is called polymorphism. Polymorphism means many forms.
Polymorphism is one of the fundamental concepts of OOP.
Polymorphism provides following features: 

  • It allows you to invoke methods of derived class through base class reference during runtime.
  • It has the ability for classes to provide different implementations of methods that are called through the same name. 
Polymorphism is of two types:
  1. Compile time polymorphism/Overloading
  2. Runtime polymorphism/Overriding
Compile Time Polymorphism
Compile time polymorphism is method and operators overloading. It is also called early binding.
In method overloading method performs the different task at the different input parameters.
Runtime Time Polymorphism
Runtime time polymorphism is done using inheritance and virtual functions. Method overriding is called runtime polymorphism. It is also called late binding.
When overriding a method, you change the behavior of the method for the derived class.  Overloadinga method simply involves having another method with the same prototype.
Caution: Don't confused method overloading with method overriding, they are different, unrelated concepts. But they sound similar.
Method overloading has nothing to do with inheritance or virtual methods.
Following are examples of methods having different overloads:
void area(int side);
void area(int l, int b);
void area(float radius);
Practical example of Method Overloading (Compile Time Polymorphism)
using System;
namespace method_overloading
{
    class Program
    {
        public class Print
        {
           
            public void display(string name)
            {
                Console.WriteLine ("Your name is : " + name);
            }
            public void display(int age, float marks)
            {
                Console.WriteLine ("Your age is : " + age);
                Console.WriteLine ("Your marks are :" + marks);
            }
        }
       
        static void Main(string[] args)
        {
            Print obj = new Print ();
            obj.display ("George");
            obj.display (34, 76.50f);
            Console.ReadLine ();
        }
    }

Note: In the code if you observe display method is called two times. Display method will work according to the number of parameters and type of parameters.

When and why to use method overloading
Use method overloading in situation where you want a class to be able to do something, but there is more than one possibility for what information is supplied to the method that carries out the task.
You should consider overloading a method when you for some reason need a couple of methods that take different parameters, but conceptually do the same thing.
Method overloading showing many forms.
using System;
namespace method_overloading_polymorphism
{
    Class Program
    {
        Public class Shape
        {
            Public void Area (float r)
            {
                float a = (float)3.14 * r;
                // here we have used function overload with 1 parameter.
                Console.WriteLine ("Area of a circle: {0}",a);
            }
            Public void Area(float l, float b)
            {
                float x = (float)l* b;
                // here we have used function overload with 2 parameters.
                Console.WriteLine ("Area of a rectangle: {0}",x);
            }
            public void Area(float a, float b, float c)
            {
                float s = (float)(a*b*c)/2;
                // here we have used function overload with 3 parameters.
                Console.WriteLine ("Area of a circle: {0}", s);
            }
        }
        Static void Main (string[] args)
        {
            Shape ob = new Shape ();
            ob.Area(2.0f);
            ob.Area(20.0f,30.0f);
            ob.Area(2.0f,3.0f,4.0f);
            Console.ReadLine ();
        }
    }
Things to keep in mind while method overloading
If you use overload for method, there are couple of restrictions that the compiler imposes.
The rule is that overloads must be different in their signature, which means the name and the number and type of parameters.
There is no limit to how many overload of a method you can have. You simply declare them in a class, just as if they were different methods that happened to have the same name.

Method Overriding:

Whereas Overriding means changing the functionality of a method without changing the signature. We can override a function in base class by creating a similar function in derived class. This is done by usingvirtual/override keywords.

Base class method has to be marked with virtual keyword and we can override it in derived class usingoverride keyword.

Derived class method will completely overrides base class method i.e. when we refer base class object created by casting derived class object a method in derived class will be called.

Example: 

// Base class
public class BaseClass
{
public virtual void Method1()
{
Console.Write("Base Class Method");
}
}
// Derived class
public class DerivedClass : BaseClass
{
public override void Method1()
{
Console.Write("Derived Class Method");
}
}
// Using base and derived class
public class Sample
{
public void TestMethod()
{
// calling the overriden method
DerivedClass objDC = new DerivedClass(); 
objDC.Method1();
 // calling the baesd class method
BaseClass objBC = (BaseClass)objDC; 
objDC.Method1();
}
}

Output
---------------------

Derived Class Method

Derived Class Method

Constructors and Destructors:

Classes have complicated internal structures, including data and functions, object initialization and cleanup for classes is much more complicated than it is for simple data structures. Constructors and destructors are special member functions of classes that are used to construct and destroy class objects. Construction may involve memory allocation and initialization for objects. Destruction may involve cleanup and deallocation of memory for objects.
  • Constructors and destructors do not have return types nor can they return values.
  • References and pointers cannot be used on constructors and destructors because their addresses cannot be taken.
  • Constructors cannot be declared with the keyword virtual.
  • Constructors and destructors cannot be declared const, or volatile.
  • Unions cannot contain class objects that have constructors or destructors.
Constructors and destructors obey the same access rules as member functions. For example, if you declare a constructor with protected access, only derived classes and friends can use it to create class objects.
The compiler automatically calls constructors when defining class objects and calls destructors when class objects go out of scope. A constructor does not allocate memory for the class object it’s this pointer refers to, but may allocate storage for more objects than its class object refers to. If memory allocation is required for objects, constructors can explicitly call the new operator. During cleanup, a destructor may release objects allocated by the corresponding constructor. To release objects, use the delete operator.

Example of Constructor

class C
{
       private int x;    
       private int y;
       public C (int i, int j)
       {
                 x = i;
                 y = j;
       }
       public void display ()     
       {
               Console.WriteLine(x + "i+" + y);
       }
}

Example of Destructor

class D
{
        public D ()
        {
            // constructor
        }         
        ~D ()
        {
           // Destructor
        }
}
If you  that this artical is helpful please subscribe me...