Thursday, 15 July 2010

Object Oriented concepts in C#

Let us see few words about C# language

C# (pronounced 'C Sharp') was developed by Microsoft Corporation and publicly announced on July 2000 as part of .NET initiative. It is simple, modern, general-purpose, object-oriented programming language. It is primarily derived from C, C++, Java and Microsoft's own Visual Basic. This is intended for use in developing software components for deployment in distributed environments; suitable for both hosted and embedded systems.
C# is used to develop applications for Microsoft .Net environment(Visual Studio). This environment incorporates different programming languages namely ASP.Net, C#, VB, C++, J#, etc. all are compiled into intermediate byte code namely MSIL(MicroSoft Intermediate Language).


HTML clipboard
Abstraction
The purpose of abstraction is to Separate the behavior of an object from the implementation of that object.

Abstract Class/Methods
An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class. Abstract classes may also define abstract methods. This is accomplished by adding the keyword abstract before the return type of the method.
HTML clipboard
Example:
Let's look at a very primitive Animal base class, which defines an abstract method for making a sound (such as a dog barking, a cat meowing).
public abstract class Animal
{
   public void eat(Food food)
   {
      // do something with food.... 
   }
   public void sleep(int hours)
   {
      try
      {
         Thread.sleep ( 1000 * 60 * 60 * 8); // 8 hours
      }
      catch (Exception ie) 
      { 
         /* ignore */ 
      }
   }
   public abstract void makeSound(); // Abstract method
}
 
Here, the 'abstract' keyword is used to denote both an abstract method, and an abstract class. Now, any animal that wants to be instantiated (like a dog or cat) must override the makeSound method.
HTML clipboard
Let's look at the derived classes Dog and Cat from nimal class.
public Dog : Animal
{
     public override void makeSound() 
     { 
         Console.WriteLine ("Lol! Lol!"); 
     }
}
public Cat : Animal
{
    public override void makeSound() 
    { 
        Console.WriteLine ("Meowh! Meowh!"); 
    }
}
HTML clipboardHTML clipboard
HTML clipboard
Abstract classes have the following features:
HTML clipboard
1. An abstract class cannot be instantiated.
2. An abstract class may contain abstract methods and accessors.
3. It is not possible to modify an abstract class with the sealed modifier because the two modifers have opposite meanings. The sealed modifier prevents a class from being inherited and the abstract modifier requires a class to be inherited.
4. A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.
Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation.

Abstract methods have the following features:
HTML clipboard
HTML clipboardHTML clipboard
1. An abstract method is implicitly a virtual method.
2. Abstract method declarations are only permitted in abstract classes.
3. Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no curly braces ({ }) following the signature. For example: public abstract void MyMethod();
4. The implementation is provided by an overriding method override, which is a member of a non-abstract class.
5. It is an error to use the static or virtual modifiers in an abstract method declaration.
6. Abstract properties behave like abstract methods, except for the differences in declaration and invocation syntax.
7. It is an error to use the abstract modifier on a static property.
8. An abstract inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.
9. An abstract class must provide implementation for all interface members.

HTML clipboard
Interface
Interfaces in C# are provided as a replacement of multiple inheritance. Because C# does not support multiple inheritance, it was necessary to incorporate some other method so that the class can inherit the behavior of more than one class, avoiding the problem of name ambiguity that is found in C++.
An interface contains only the signatures of methods, delegates or events. The implementation of the methods is done in the class that implements the interface, as shown in the following example:
interface ISampleInterface
{
    void SampleMethod();
}
class ImplementationClass : ISampleInterface
{
    // Explicit interface member implementation: 
    Void SampleMethod()
    {
        // Method implementation.
    }
    static void Main()
    {
        // Declare an interface instance.
        ISampleInterface obj = new ImplementationClass();
 
        // Call the member.
        obj.SampleMethod();
    }
}

Abstraction
An interface has the following properties:
1. An interface is like an abstract base class: any non-abstract type that implements the interface must implement all its members.
2. An interface cannot be instantiated directly.
3. Interfaces can contain events, indexers, methods, and properties.
4. Interfaces contain no implementation of methods.
5. Classes and structs can implement more than one interface.
6. An interface itself can inherit from multiple interfaces.

Difference between Interface and Abstract methods
1. Interface contains methods that must be abstract; abstract class may contain concrete methods.
2. Interface contains variables that must be static and final; abstract class may contain non-final and final variables.
3. Interface can "extends" another interface, abstract class can "extends" another class and "implements" multiple interfaces.
4. Interface is absolutely abstract; abstract class can be invoked if a main() exists.
5. Interface is more flexible than abstract class because one class can only "extends" one super class, but "implements" multiple interfaces.
6. Members in an interface are public by default; abstract class may contain non-public members.
7. Interface is used to "implements"; whereas abstract class is used to "extends".
8. Interface can be used to achieve multiple inheritance; abstract class can be used as a single inheritance.

HTML clipboard
Polymorphism
Polymorphism is the capability of a single class to behave in multiple ways. It allows you to invoke derived class methods through a base class reference during run-time.
This is handy when you need to assign a group of objects to an array and then invoke each of their methods. They won't necessarily have to be the same object type. However, if they're related by inheritance, you can add them to the array as the inherited type. Then if they all share the same method name, that method of each object can be invoked.


Encapsulation
Encapsulation provides a way to bind together code and data, keeping both safe from outside interference or misuse.
Through Encapsulation, the user of a component need know only how to interact with the Component, not how it works. The user of a component doesn’t need to know the Format and layout of the data within the component and its algorithms. And the user needn’t know in what language the module was written.

HTML clipboard
There are two ways of encapsulating or hiding the data.
CREATING METHODS TO HIDE DATA : we define an accessor (get method) and mutator (set method).
HTML clipboardusing system;
public class Department
{
   private string departname;
   .......
   // Accessor.
  
public string GetDepartname()

   {
      return departname;
   }
   // Mutator.
  
public void SetDepartname( string a)
   {
     departname=a;
   }
}


HTML clipboard
USING PROPERTIES TO HIDE DATA : The second way to control access to data within a class file is by using properties
using system;
public class Department
{
   private string departname;
   public string Departname
   {
     get
    
{
       return departname;
     }
     set
     {
       departname=value;
     }
   }
}
public class Departmentmain
{
   public static int Main(string[] args)
   {

     Department d= new Department();
     d.departname="Communication";
     Console.WriteLine("The Department is :{0}",d.Departname);
     return 0;
   }
}


Inheritance
One of the key concepts of Object Oriented Programming is nothing but inheritance. By using the concept of inheritance, it is possible to create a new class from an existing one and add new features to it. Thus inheritance provides a mechanism for class level re usability.
class Base
{
    // something
}
class Derived : Base
{
    // some more thing
} 
The operator ‘:’ is used to indicate that a class is inherited from another class. Remember that in C#, a derived class can’t be more accessible than it’s base class. That means that it is not possible to declare a derived class as public, if it inherits from a private class. For example the following code will generate a compile time error.