Monday, September 27, 2010

Static Polymorphism:


Static Polymorphism:

Function Overloading:

            Using  the same name for two or more functions is called function overloading. Each redefinition of a function must use different types of parameters, sequence of parameters, or a number of parameters. The type , seqeuence , or number of parameters for  a function is called function signature. Same is briefly explained as follows.

The number of parameters.

  • void add(int a);
  • void add( int a, float b);

The type of parameters.

  • void display(char a);
  • void add(int  b);

The sequence of parameters

  • void add(int a, char b);
  • void add( char a, int b);

The most important thing ‘return type’  is not part of function signature. Therefore the followign two declarations cannot occur in the same class.

  • void add();
  • char add();

Program 15:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Csharp
{
    class polymorphism
    {
     
        public static void Main(string[] args)
        {
            polymorphism obj = new polymorphism();
            obj.add(2.3F, 3.2F);
            obj.add(2, 3);
            obj.add(2.6m, 3.2m);
            obj.disp('b', 5);
            obj.disp(5, 'b');
            obj.display('b');
            obj.display(5, 'b');
            Console.ReadLine();
          
        }
        ///

        /// (a)Type of parameters
        ///
        public void add(int a, int b)
        {
            int sum;
            sum = a + b;
            Console.WriteLine("{0}", sum);
        }
        public void add(float a, float b)
        {
            float sum;
            sum = a + b;
            Console.WriteLine("{0}", sum);
        }
        public void add(decimal a, decimal b)
        {
            decimal sum;
            sum = a + b;
            Console.WriteLine("{0}", sum);
        }
        /// (b)number of parameters
        ///

        ///
        public void display(int a,char b)
        {
          
            Console.WriteLine("{0}{1}", a,b);
        }
        public void display(char a)
        {
         
            Console.WriteLine("{0}", a);
        }
        ///
        /// (c)seqeunce of parameters
        ///
        public void disp(int a, char b)
        {
         
            Console.WriteLine("{0}{1}", a, b);
        }
        public void disp(char b, int a)
        {
        
            Console.WriteLine("{0}{1}", a, b);
        }
    }
   
}

Sunday, September 26, 2010

Dynamic Polymorphism: Abstract Classes and Interfaces


Dynamic Polymorphism:

Abstract Classes

An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

1.Abstract class is a special kind of class that cannot be instantiated.
2.Abstract class can be only be inherited.
3.It is used to maintain the subclass in same hierarchies or standards.
4.Abstract class can have both abstract methods,virtual methods and non-abstract methods.
5.To define an abstract methods override keyword is used in the derived class.
6.Multiple inheritance of abstract classes is not possible.
7.Access Modifiers can be used in abstract classes.
8.Abstract classes can contain fields.
  
Interfaces:
           
            An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesnt support multiple inheritance, interfaces are used to implement multiple inheritance.
  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Csharp
{
    class interfaces
    {
        public  static void Main(string [] args)
        {
            implements obj = new implements();
            obj.add();
            obj.delete();
            obj.search();
            obj.update();
            Console.ReadLine();

        }
    }
    interface command
    {
        void add();
        void update();
        void delete();
        void search();

    }
    class implements : command
    {

        #region command Members

        public void add()
        {
            Console.WriteLine("Performs insertion operations");
        }

        public void update()
        {
            Console.WriteLine("Performs update operations");
        }

        public void delete()
        {
            Console.WriteLine("Performs delete operations");
        }

        public void search()
        {
            Console.WriteLine("Performs search operations");
        }

        #endregion
    }
}

Abstract Methods and Virtual Methods

abstract methods  are incomplete and they can only be defined in the inherited classes.Abstract methods can only be defined in the abstract classes.

The virtual function could be implemented by the inherited classees in their own way and the call to the method is decided at runtime. Virtual Methods can be overriden in the inherited classes.

Program 17:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Csharp
{
    class AbstractClasses
    {
        public static void Main(string[] args)
        {
            cmmd obj = new cmmd();
            obj.add();
            obj.delete();
            obj.search();
            obj.update();
            Console.ReadLine();
        }
      
      
    }
    abstract class commands
    {
        public int a, b, res;
       
        public abstract void add();
            //uncommenting this lines generates an error;
        //{
        //    Console.WriteLine("The result operation is performed");
        //}
        public virtual void delete()
        {

        }
        public abstract void search();
       
        public void update()
        {
            Console.WriteLine("Performs update operations");
        }
    }
    class cmmd : commands
    {
        public override void add()
        {
            Console.WriteLine("Performs insertion operations");
        }

        public override void search()
        {
            Console.WriteLine("Performs search operations");
        }
        public override void delete()
        {
            Console.WriteLine("Performs delete operations");
        }
    }

}

Saturday, September 25, 2010

Sealed,Partial Classes and Inheritance


Sealed Classes:

Classes which cannot be inherited are nothing but sealed classes.

Partial Classes:

It is possible to split the definition of a class or a struct, or an interface over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled.

Inheritance:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Csharp
{
    class Inhertiance
    {
        public static void Main(string[] args)
        {
            Reptiles obj = new Reptiles();
            obj.Birds();
            obj.Mammals();
            obj.reptiles();
            Console.ReadLine();
        }
     
    }
    class animals
    {
        public void Mammals()
        {
            Console.WriteLine("The rat belongs to mammals family");
        }
        public void Birds()
        {
            Console.WriteLine("The eagle belongs to birds family");
        }
    }
    class Reptiles : animals
    {
        public void reptiles()
        {
            Console.WriteLine("The snake belongs to reptiles familY");
        }
    }
}

Friday, September 24, 2010

Working with Collection classes C Sharp

Working with Collections:
Dot net Base Class library provides number of collection class to work with. Generally collection classes are used to group related objects. The collection classes are designed in order to overcome the limitations of the arrays. Most of the collections classes have methods to add, delete, find, sort, reverse and many more. By using the collection classes we can increase the size dynamically and we can retrieve the information by using the key which is a string value, besides using the index. Most of the common collection classes are Stack, Heaps, Queue, Array List and Hashtable. Hashtable allows retrieving the information from the collection based key-value pair.

Working with ArrayList:
The ArrayList class is most commonly used collection class in the system.collections namespace.
Consider the previous example of categories and products, by using the ArrayList class we can work with the records of the customers more efficiently.
Common Methods used in ArrayList():
ArrayList list = new ArrayList ();
ADD():
Adding individual items to the array list.
list.Add(“FM Transmitter”);
list.Add(“DJ Cable”);
list.Add(“Adapter”);
AddRange():
To add a specified range of elements to array list.
string[ ] products = { "FM Transmitter ", "DJ Cable ", " Adapter " };
list.AddRange (products);

BinarySearch():
Is used to search entire list.
list.BinarySearch("FM Transmitter ") returns index value as 0.
 
Contains():
Is used to determine whether an element is in the list.
list.Contains("DJ Cable"). returns a true or false based on the parameter.

CopyTo():

copies entire list to the specified array, starting at the beginning of the target array.
string[ ] products = {“FM Transmitter ", "DJ Cable ", “Adapter " };
list.AddRange(products);           
string[ ] b = new string[3];
list.CopyTo(b);

GetRange():
GetRange method is used to extract the range of elements or to create a new collection of elements from an existing list.
string[,] c = new string[2,2] { {"hello","hi"},{"hello","hi"} };
list.Add(c);       
foreach (string [,]f in list.GetRange(0, 1))
        {
                Console.WriteLine("{0}.{1}",f[0,0],f[0,1]);
         }

Indexof():
 Is used to find the index of an element in the ArrayList.
list.IndexOf(" Adapter"); returns the zero based index value as 2.

Insert():
Is used to add an element at a specified index.
ArrayList list = new ArrayList();
list.Insert(0,"HeadPhoe");

InsertRange():
Is used to add a specified range of items to array list at a specified index:
string[ ] products = {“FM Transmitter ", "DJ Cable ", “Adapter " };
list.AddRange(products);           
list.InsertRange (0, products);
In order to add values to the categories, products and customer sections. We need to create classes for each one of the section. For time being we will create products class and category class.

Remove:
Is used to remove an item from the array depending on the given string value.
ArrayList list = new ArrayList();
list.Add("FM Transmitter");
list.Add("DJ Cable");
list.Add("Adapter");
list.Remove("Adapter");

RemoveAt:
Is used to remove an element from the array list at a specified index:
ArrayList list = new ArrayList();
list.Add("FM Transmitter");
list.Add("DJ Cable");
list.Add("Adapter");
list.RemoveAt(0)

Sort() and Reverse():
Is used to sort and reverse the array list.
ArrayList list = new ArrayList();
list.Add("FM Transmitter");
list.Add("DJ Cable");
list.Add("Adapter");
list.Sort();
list.Reverse();

Note:
Difference between Add and AddRange: If u r using Add method to add elements in the array list, each element occupies a single index and by if u r using AddRange method the collection of elements are inserted at a single index.

Using ArrayList to maintain product objects:
 For example consider u have an products class as follows,  u can work with it by using Array List class as follows:
public class products
    {
        private string id, name, price;
        // constructor
        public  products()
        {

        }
        public products(string _id, string _name, string _price)
        {
            id = _id;
            name = _name;
            price = _price;
        }
        public string ID
        {
            get
            {
                return id;
            }
            set
            {
                id = value;
            }
        }
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }
        public string Price
        {
            get
            {
                return price;
            }
            set
            {
                price = value;
            }
        }
    }
Using ArrayList AddRange Method():
ArrayList products = new ArrayList();
products.AddRange(new products[] { new products("FMT","FM Transmitter","$43"),new products("DJC","DJ Cable","$54") });   

Using ArrayList Add Method():
ArrayList products = new ArrayList();
products p1 = new products("FMT", "FM Transmitter", "$43");
products p2 = new products("DJC", "DJ Cable", "$54");
products.Add(p1);
products.Add(p2);
Next :
Working with Stack.
Further Reading:
Msdn - Array List