Sunday, 8 December 2013

Access Specifiers in C#.Net

What is Access Specifiers in C#?
Access Specifiers defines the scope of a class member. A class member can be variable or function. In C# there are five types of access specifiers are available.



The class member, that is defined as public can be accessed by other class member that is initialized outside the class. A public member can be accessed from anywhere even outside the namespace.
Example:
using System;

namespace Public_Access_Specifiers
{
  class access
   {
     // String Variable declared as public
     public string name;
     // Public method
     public void print()
      {
        Console.WriteLine("\nMy name is "+name);
      }
   }

  class Program
   {
     static void Main(string[] args)
      {
        access ac = new access();
        Console.Write("Enter your name:\t");
        // Accepting value in public variable that is               outside the class
        ac.name = Console.ReadLine();
        ac.print();

        Console.ReadLine();
      }
   }
}


The private access specifiers restrict the member variable or function to be called outside from the parent class. A private function or variable cannot be called outside from the same class. It hides its member variable and method from other class and methods. However, you can store or retrieve value from private access modifiers using get set property. You will learn more about get set property in lateral chapter.
Example:

using System;

namespace Private_Access_Specifiers
{
  class access
   {
     // String Variable declared as private
     private string name;
     public void print() // public method
      {
        Console.WriteLine("\nMy name is " + name);
      }
   }

  class Program
   {
     static void Main(string[] args)
      {
        access ac = new access();
        Console.Write("Enter your name:\t");
        // raise error because of its protection level
        ac.name = Console.ReadLine();
        ac.print();
        Console.ReadLine();
      }
   }
}


The protected access specifier hides its member variables and functions from other classes and objects. This type of variable or function can only be accessed in child class. It becomes very important while implementing inheritance.
Example:

using System;
 
namespace Protected_Specifier
{
  class access
   {
     // String Variable declared as protected
     protected string name;
     public void print()
      {
        Console.WriteLine("\nMy name is " + name);
      }
   }
 
  class Program
   {
     static void Main(string[] args)
      {
        access ac = new access();
        Console.Write("Enter your name:\t");
        // raise error because of its protection level
        ac.name = Console.ReadLine();
        ac.print();
        Console.ReadLine();
      }
   }
}


The internal access specifier hides its member variables and methods from other classes and objects, that is resides in other namespace. The variable or classes that are declared with internal can be access by any member within application. It is the default access specifiers for a class in C# programming.
Example:

using System;
 
namespace Internal_Access_Specifier
{
  class access
   {
     // String Variable declared as internal
     internal string name;
     public void print()
      {
        Console.WriteLine("\nMy name is " + name);
      }
   }
 
  class Program
   {
     static void Main(string[] args)
      {
        access ac = new access();
        Console.Write("Enter your name:\t");
        // Accepting value in internal variable
        ac.name = Console.ReadLine();
        ac.print();
        Console.ReadLine();
      }
   }
}



The protected internal access specifier allows its members to be accessed in derived class, containing class or classes within same application. However, this access specifier rarely used in C# programming but it becomes important while implementing inheritance.
Example:

using System;
 
namespace Protected_Internal
{
  class access
   {
     // String Variable declared as protected internal
     protected internal string name;
     public void print()
      {
        Console.WriteLine("\nMy name is " + name);
      }
   }
 
 
  class Program
   {
     static void Main(string[] args)
      {
        access ac = new access();
        Console.Write("Enter your name:\t");
        // Accepting value in protected internal variable
        ac.name = Console.ReadLine();
        ac.print();
        Console.ReadLine();
      }
   }
}

Partial class C#.Net

Introduction
A Partial class is one that can be split among multiple physical files. This feature was introduced with the release of C# version 2.0. With C#, we can split the source code for a class into separate files so that we can organize the definition of a large class into smaller, easier to manage pieces. When we split a class across multiple files, we define the parts of the class by using the partial keyword in each file. Each file contains a section of the class definition, and all parts are combined when the application is compiled. Look at the example below:

Original and Single Class File (Calculation.cs)
class ClassRoom
{
    
private int boycount;   //field
    public ClassRoom()     //default constructor
    
{
        
boycount = 30;
    
}
    public ClassRoom(int bcount)     //overloaded constructor
    
{
        
boycount = bcount;
    
}
    public double Avg()     //method
    
{
        
//statements goes here
    
}
}

Splitted Class Files into two parts
//Calculation1.cs
partial class ClassRoom
{
    
private int boycount;   //field

    
public ClassRoom()     //default constructor
    
{
        
boycount = 30;
    
}
}
//Calculation2.cs
partial class ClassRoom
{
    
public ClassRoom(int bcount)     //overloaded constructor
    
{
        
boycount = bcount;
    
}
    public double Avg()     //method
    
{
        
//statements goes here
    
}
}
Now, when we compile a class that has been split into separate files, we must provide all the files to the compiler.
Partial Classes Rules and Advantages
To work on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously.
When working with automatically generated source, code can be added to the class without having to recreate the source file.
To split a class definition, use the partial keyword modifier.
All the parts must have the same accessibility, such as public, private, and so on.
The partial modifier can only appear immediately before the keywords class, struct, or interface.

Wednesday, 9 October 2013

All about Abstract in C#

                             

                                                       All about abstract in C#   (अ ज य )

You will find in this Post -
What is Abstract in c# ?
Why we use Abstract ?
What is  Abstract method, Abstract Class?
When we use abstract ?
How Abstract class is different from interface ?
Difference between Static and abstract class ?


What is Abstract in c# ?

The abstract modifier indicates that the thing being modified has a missing or incomplete implementation. The abstract modifier can be used with classes, methods, properties, indexers, and events. Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class.


abstract class absClass
      {
            //A Non abstract method
            public int AddTwoNumbers(int Num1, int Num2)
            {
                return Num1 + Num2;
            }

            //An abstract method, to be
         
 public abstract int MultiplyTwoNumbers(int Num1, int Num2);
      }

Abstract method 


When an instance method declaration includes an abstract modifier, that method is said to be an abstract method. Although an abstract method is implicitly also a virtual method, it cannot have the modifier virtual.
An abstract method declaration introduces a new virtual method but does not provide an implementation of that method. Instead, non-abstract derived classes are required to provide their own implementation by overriding that method. Because an abstract method provides no actual implementation, the method-body of an abstract method simply consists of a semicolon.
Abstract method declarations are only permitted in abstract classes
public abstract class Shape
{
   public abstract void Paint(Graphics g, Rectangle r);
}
public class Ellipse: Shape
{
   public override void Paint(Graphics g, Rectangle r) {
      g.DrawEllipse(r);
   }
}
public class Box: Shape
{
   public override void Paint(Graphics g, Rectangle r) {
      g.DrawRect(r);
   }
}
In below code sample a compile-time error is reported for the base.F() invocation because it references an abstract method.
abstract class A
{
   public abstract void F();
}
class B: A
{
   public override void F() {
      base.F();                  // Error, base.F is abstract
   }
}

NOTE: An abstract method declaration is permitted to override a virtual method. This allows an abstract class to force re-implementation of the method in derived classes, and makes the original implementation of the method unavailable. In the example
class A
{
   public virtual void F() {
      Console.WriteLine("A.F");
   }
}
abstract class B: A
{
   public abstract override void F();
}
class C: B
{
   public override void F() {
      Console.WriteLine("C.F");
   }
}
class A declares a virtual method, class B overrides this method with an abstract method, and class C overrides the abstract method to provide its own implementation.


Abstract Class

  • An abstract class means that, no object of this class can be instantiated, but can make derivations of this.
  • An abstract class can contain either abstract methods or non abstract methods. Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class.
  • Abstract class does not mean that it should contain abstract members. Even we can have an abstract class only with non abstract members.
  • An abstract class cannot be a sealed class.
  • Declaration of abstract methods are only allowed in abstract classes.
  • An abstract method cannot be private.
  • The access modifier of the abstract method should be same in both the abstract class and its derived class. If you declare an abstract method as protected, it should be protected in its derived class. Otherwise, the compiler will raise an error.
  • An abstract method cannot have the modifier virtual. Because an abstract method is implicitly virtual.
  • An abstract member cannot be static.
Sample Code -


namespace ConsoleApplication1
{
  

      //Creating an Abstract Class
      abstract  class absClass
      {
            //A Non abstract method
            public int AddTwoNumbers(int Num1, int Num2)
            {
                return Num1 + Num2;
            }

            //An abstract method, to be
            //overridden in derived class
            public abstract int MultiplyTwoNumbers(int Num1, int Num2);
      }

      //A Child Class of absClass
        class absDerived:absClass
      {
           
            static void Main(string[] args)
            {
               //You can create an
               //instance of the derived class

               absDerived calculate = new absDerived();
               int added = calculate.AddTwoNumbers(10,20);
               int multiplied = calculate.MultiplyTwoNumbers(10,20);
               Console.WriteLine("Ajay's Blog For Abstract Class-");
               Console.WriteLine("Added : {0}, Multiplied : {1}", added, multiplied);
               Console.ReadKey();
            }

            //using override keyword,
            //implementing the abstract method
            //MultiplyTwoNumbers
            public override int MultiplyTwoNumbers(int Num1, int Num2)
            {
                return Num1 * Num2;
            }
      }
}

When to use abstract Class

  • If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.
  • If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
  • If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
  • If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
Some Other Points

  • When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning. This is the practice used by the Microsoft team which developed the Base Class Library. ( COM was designed around interfaces.)
  • Use an abstract class to define a common base class for a family of types.
  • Use an abstract class to provide default behavior.
  • Subclass only a base class in a hierarchy to which the class logically belongs.


How Abstract class is different from interface


  • An Interface cannot implement methods.
  • An abstract class can implement methods.

  • An Interface can only inherit from another Interface.
  • An abstract class can inherit from a class and one or more interfaces.

  • An Interface cannot contain fields.
  • An abstract class can contain fields.

  • An Interface can contain property definitions.
  • An abstract class can implement a property.

  • An Interface cannot contain constructors or destructors.
  • An abstract class can contain constructors or destructors.

  • An Interface can be inherited from by structures.
  • An abstract class cannot be inherited from by structures.

  • An Interface can support multiple inheritance.
  • An abstract class cannot support multiple inheritance.