Thursday, November 15, 2012

Polymorphism

Polymorphism :

A Method or function will show different behaviours when we pass different no of arguments or different type of arguements to a method.A method can have more forms.This concept is called Polymorhism.

Polymorphism is one of the fundamental concepts of OOP.

Polymorphism provides following features: 

  
1. It allows you to invoke methods of derived class through base class reference during runtime.
2. 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 / Static Polymorphism / Overloading
2.  Run time polymorphism / Dynamic 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.  Overloading a 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)
:





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.

Imporant :

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.








 






Monday, November 5, 2012

Difference Between XML and HTML

Differences Between HTML and XML

HTML is an abbreviation for HyperText Markup Language while XML stands for eXtensible Markup Language.The differences are as follows:-


1.HTML was designed to display data with focus on how data looks while XML was designed to be a software and hardware independent tool used to transport and store data, with focus on what data is.


2.HTML is a markup language itself while XML provides a framework for defining markup languages.


3.HTML is a presentation language while XML is neither a programming language nor a presentation language.


4.HTML is case insensitive while XML is case sensitive.


5.HTML is used for designing a web-page to be rendered on the client side while XML is used basically to transport data between the application and the database.


6.HTML has it own predefined tags while what makes XML flexible is that custom tags can be defined and the tags are invented by the author of the XML document.


7.HTML is not strict if the user does not use the closing tags but XML makes it mandatory for the user the close each tag that has been used.


8.HTML does not preserve white space while XML does.


9.HTML is about displaying data,hence static but XML is about carrying information,hence dynamic.


Thus,it can be said that HTML and XML are not competitors but rather complement to each other


and clearly serving altogether different purposes.

Friday, September 21, 2012

Constructors

Constructors : 
 
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.
  • 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.

Constructors are classified into two types in c#.
They are

 1. Instance Constructors
 2.Non Instance Constructors

 Instance Constructors :

In Instance constructors. again we have 4 types of constructors.they are
1.Default Constructor
2.Parametrized
3.Copy Constructor
4.Private Constructor.

Noninstance Constructor :

We have only one constructor. ie Static Constructor


 

Thursday, September 13, 2012

Wednesday, September 12, 2012

Encapsulation and Inheritance

Encapsulation
Encapsulation is a process of binding the data members and member functions into a single unit.
Example 
A class can contain data fields and methods.
Consider the following class
public class 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.



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. 

There are 5 types of inheritances in C#. they are

1.Single Inheritance
2.Multilevel INheritance
3.Multiple Inheritance
4.Hybrid Inheritance
5.Hierarchical inheritance.


Single Inheritance :

when a single derived class is created from a single base class then the inheritance is called as single inheritance.

Different types of inheritance 
 
Program :
 
using System;
namespace ProgramCall

{
   class BaseClass

    {
      //Method to find sum of give  2 numbers

        public int FindSum(int x, int y)

        {

          return (x + y);

        }

        //method to print given 2 numbers

        //When declared protected , can be accessed only from inside the derived class

        //cannot access  with the instance of  derived class

        protected void Print(int x, int y)

        {

            Console.WriteLine("First Number: " + x);

            Console.WriteLine("Second Number: " + y);

         }

    }


    class Derivedclass : BaseClass

    {

      public void Print3numbers(int x, int y, int z)

        {

            Print(x, y); //We can directly call baseclass members

            Console.WriteLine("Third Number: " + z);

        }


    }

     class MainClass

    {

      static void Main(string[] args)

        {

            //Create instance for derived class, so that base class members
            // can also  be accessed

            //This is possible because  derivedclass is inheriting base class

             Derivedclass instance = new Derivedclass();

            instance.Print3numbers(30, 40, 50); //Derived class internally calls base class method.

            int sum = instance.FindSum(30, 40); //calling base class method with derived class instance

            Console.WriteLine("Sum : " + sum);

            Console.Read();

        }

    }

}

Output

First Number: 30
Second Number: 40
Third Number: 50
Sum : 70

OOPS Part -1

What is OOP?

OOP is a design philosophy. It stands for Object Oriented Programming. Object-Oriented Programming (OOP) uses a different set of programming languages than old procedural programming languages (C, Pascal, etc.). Everything in OOP is grouped as self sustainable "objects". Hence, you gain re-usability by means of four main object-oriented programming concepts. 

In order to clearly understand the object orientation, let’s take your “hand” as an example. The “hand” is a class. Your body has two objects of type hand, named left hand and right hand. Their main functions are controlled/ managed by a set of electrical signals sent through your shoulders (through an interface). So the shoulder is an interface which your body uses to interact with your hands. The hand is a well architected class. The hand is being re-used to create the left hand and the right hand by slightly changing the properties of it. 

What is a Class?

A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe the details of an object. A class is the blueprint from which the individual objects are created. Class is composed of three things: a name, attributes, and operations. 

Ex :
public class Employee
{
}
  
Creating object :
 
Employee obj=new Employee(); 
 

According to the sample given above ,we can say that the student object, named objectStudent
has created out of the Student class.
 
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. 
 

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.
 In pure OOP terms an object is an instance of a class.
Class is composed of three things name, attributes, and operations .

OOPS Features : 

If any programming language wants to be a object oriented programming language. then it needs to satisfy class and objects. then it needs to satisfy following four features. they are

1.Encapsulation
2.Inheritance
3.Polymorphism
4.Data abstraction.

C#  is strong object oriented programming language.

Access Modifiers in c# :

Access Modifier Description (who can access)
private Only members within the same type. (default for type members)
protected Only derived types or members of the same type.
internal Only code within the same assembly. Can also be code external to object as long as it is in the same assembly. (default for types)
protected internal Either code from derived type or code in the same assembly. Combination of protected OR internal.
public Any code. No inheritance, external type, or external assembly restrictions.

Accessibility :
 
Public - any item in the current assembly or any assembly that references the class, can access this member.
Protected - access is limited to the containing class or types derived from the containing class.
Internal - any item in the current assembly can access this member.
Protected internal - access is limited to the current assembly or types derived from the containing class.
Private - access is limited to the containing class. 


Class Members in c# : 

In C#, a class have following members,.
1.Data fields
2.Methods
3.Constructors
4.Destructors
5.Properties
6.Events
7.indexers.

Fields - instances of objects that are considered part of a class, normally holding class data.
 

Properties - methods on a class that are accessed as if they were fields on that class. A property can provide protection for a class field to keep it from being changed without the object's knowledge. For a more detailed understanding see Fields and Properties.

Methods - these define the actions that a class can perform by actioning a series of statements. Methods can take parameters that provide input data, and can return output data through parameters. Methods can also return a value directly, without using a parameter. 


Events - a way of providing notifications about occurrences, such as button clicks or the successful completion of a method, to other objects. Events are defined and triggered using delegates. 


Delegates - a type safe container of one or more function pointers.


Operators - these are terms or symbols such as +, *, <, and so on that perform operations on operands. Operators can be redefined to perform operations on custom data types.  


Indexers - these allow an object to be indexed in a manner similar to arrays.  

Constructors - methods that are called when the object is first created. They are often used to initialize the object's data.

Destructors - methods that are called by the runtime execution engine when the object is about to be removed from memory. They are generally used to make sure that any resources which need to be released are handled appropriately.
 

Constants - data members that are known at compile time.


 
 

Pointers, Call by Value & Reference

Pointers : 

C# also supports pointers in a limited extent. A pointer is nothing but a variable that holds the memory address of another type. But in C# pointer can only be declared to hold the memory address of value types and arrays. Unlike reference types, pointer types are not tracked by the default garbage collection mechanism. For the same reason pointers are not allowed to point to a reference type or even to a structure type which contains a reference type. We can say that pointers can point to only unmanaged types which includes all basic data types, enum types, other pointer types and structs which contain only unmanaged types.  


The general form of declaring a pointer type is as shown below 
       
type *variable_name;  

Where * is known as the de-reference operator. For example the following statement 

int *x ; 
Declares a pointer variable x, which can hold the address of an int type. The reference operator (&) can be used to get the memory address of a variable.  

int x = 100; 

The &x gives the memory address of the variable x, which we can assign to a pointer variable
 
int *ptr = & x;.

Console.WriteLine((int)ptr) // Displays the memory addressConsole.WriteLine(*ptr) // Displays the value at the memory address. Unsafe Codes :

The C# statements can be executed either as in a safe or in an unsafe context. The statements marked as unsafe by using the keyword unsafe runs out side the control of Garbage Collector. Remember that in C# any code involving pointers requires an unsafe context. 
We can use the unsafe keyword in two different ways. It can be used as a modifier to a method, property, and constructor etc. For example          using System;
class MyClass
{
static void Main(string[] args)
        {
            unsafe
            {
                int a = 10;
                int* ptr = &a;  //pointer valriable
                Console.WriteLine("value of a :" + (*ptr));
                Console.WriteLine("address of a :"+(int)ptr);
                Console.Read();
            }
        }




Pointers & ConversionsIn C# pointer types do not inherit from object and no conversion exists between pointer types and objects. That means boxing and un-boxing are not supported by pointers. But C# supports conversions between the different pointer types and pointer types and integral types. 
C# supports both implicit and explicit pointer conversions within un-safe context. The implicit conversions are

  1. From any type pointer type to void * type.
  2. From null type to any pointer type.
The cast operator (()) is necessary for any explicit type conversions. The explicit type conversions are
  1. From any pointer type to any other pointer type.
  2. From sbyte, byte, short, ushort, int, uint, long, ulong to any pointer type.
  3. From any pointer type to sbyte, byte, short, ushort, int, uint, long, ulong types.
For example

char c = 'R';
char *pc = &c;
void *pv = pc; // Implicit conversionint *pi = (int *) pv; // Explicit conversion using casting operator 


Call by Value : 

In call by value method, the called function creates a new set of variables and copies the values of arguments into them.

To be more precise any changes that take place inside the calling method have no affect on the original value of the variable.Look the example below.Here in our example original value of a is 10 .When it is passed to "callByValue" method a is incremented.But it is not reflected in the main method and hence the final value of a remains same ie 10.

Pass by Reference: 


Any changes that take place inside the calling method will affect the original value of the variable."ref" keyword must be used in the calling method & called method.


Here in our example original value of a is 10 .When it is passed to "callByRef" method, a is incremented and also reflected in the main method and hence the final value of a is 20.
 Example :

public static void callByValue(int x)
        {
            x = x + x;
            Console.WriteLine("Sum : " + x);
        }
        public static void callByRef(ref int x)
        {
             x=x+x;
            Console.WriteLine("Sum : " + x);
        }
        static void Main(string[] args)
        {
                int a = 10;
                callByValue(a);
                Console.WriteLine("a value after call by val :" + a);
                callByRef(ref a);
                Console.WriteLine("a value after callby Ref :" + a);
                Console.Read();
            }
          
        }