Monday, 10 February 2014

Exception Handling in C#

                                                                                                                                                                                                Previous....
                                                                                                                                                                                                    Next......


An exception is an error Which occurs during a program is running. 
C# exception handling has four keywords: trycatchfinally and throw.

Try: A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks.

catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.

finally: The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.

throw: A program throws an exception when a problem shows up. This is done using a throw keyword.

Syntax

try
{
   // a statements 
}
catch( Exception e1 )
{
   // error handling code
}

finally
{
   // statements to be executed
}
     This article talks about best practices of exception handling, and guides you for some common programming mistakes developers do, as that seems appropriate in most applications written.

Best practices are only guidelines and do not enforce you to follow these, but if followed correctly then you won't only write less lines of code, but you work and code with more logical approach of coding and designing the code modules.


#1 Do Not Throw Exceptions to Control Application Flow

Scenario

The following code throws an exception inappropriately, when a supplied product is not found


.
public static void CheckProductExists(int ProductId)
{
    //... search for Product    if (ProductId == 0) // no record found throw error    {
        throw (new Exception("Product is  Not found in inventory"));
    }
    else    {
        Console.WriteLine("Product is available");
    }
}

static void Main(string[] args)
{   
     Console.WriteLine("Enter a ProductId you would like to search [1 – 100]"); 
     
 int productId = Int32.Parse(Console.ReadLine());
 
      CheckProductExists(productId);
      Console.ReadLine();
}

After execution of Main, and when 0 is passed as shown in Figure 1-1 below.
 Figure 1-1 Reading productId from Console

The value being passed to the program as shown in Figure 1-1 will result in an exception as shown in Figure 1-2 below.


Problem

Throwing an exception as shown in Scenario section and Figures 1-1 and 1-2 is expensive; presumably throwing an exception causes the CPU to fetch code and data it would otherwise not have executed. You probably should not throw any exceptions in that scenario.

Solution

Consider the possibility that the code shown above not finding a product is an expected condition. Hence, re-factor the code to return a value that indicates the search result after the method's execution. The following code re-writes the code to verify the availability of the product in inventory and sets a flag to true or false. 

This apparently avoids a new exception being thrown. The calling code uses a flag value to identify whether the inventory has the specified product or not.


public static bool CheckProductExists(int productId)
{
    //... search for Product    if (productId == 0) // no record found    {
        return false;
    }
    else    {
        return true;
    }
}

static void Main(string[] args)
{
    Console.Write("Enter a ProductId you would like to search [1 – 100] : "); 
    int productId = Int32.Parse(Console.ReadLine());

    if
 (!CheckProductExists(productId) == false)
    {
        Console.WriteLine("Found");
    }
    
else
    {
         Console.WriteLine("Not Available");
    }

    Console.ReadLine();}


#2 Use Validation Code to Reduce Unnecessary Exceptions
Scenario

Using a try/catch block can be a very handy solution for most programming situations, for example the most commonly known is DivideByZero. The following code uses a try/catch block to handle DivideByZero and that is pretty convincing.


static void Main(string[] args)
{
    Console.Write("Enter numerator : "); 
    int numerator = Int32.Parse(Console.ReadLine());

    Console.Write("Enter divisor : ");
    int divisor = Int32.Parse(Console.ReadLine());

    try    {
        double result = numerator / divisor;
        Console.WriteLine(result);
    }
    catch (DivideByZeroException ex)
    {
        Console.WriteLine(ex.Message);
    }
    
    Console.ReadLine();
}
Problem

There is no need to perform exception handling if we can use the basic validation techniques before code is executed. In this scenario an exception only needs to be handled if the divisor is 0 (zero) otherwise it should work fine.

Solution

Let's re-factor the code and rewrite it so try/catch blocks can be avoided, and as a result is more efficient.
 


static void Main(string[] args)
{
    Console.Write("Enter nemerator : ");
    int numerator = Int32.Parse(Console.ReadLine());

    Console.Write("Enter divisor : ");
    int divisor = Int32.Parse(Console.ReadLine());

    if (divisor != 0)
    {
        Console.WriteLine(numerator / divisor);
    }
    else
    {
        Console.WriteLine(Double.NaN);
    }
   
    Console.ReadLine();
}
Figure 1-4 Using validation code instead to avoid try/catch to handle an exception


                                                                                                    
                                                                                                                                                                                           Previous....
                                                                                                                                                      Next...

Struct in C#

                                                                                                                                Previous....

                                                                                                                                    Next...... 


In C#, a structure is a value type data type. so it is stored in stack and it use enum,delegate and there may be constructor or not. The struct keyword is used for creating a structure.
Defining a Structure
structure is a homogeneous datatype means there can be more then one datatype. 
For example, here is the way you would declare the Book structure:
struct student
{
   public string name;
   public int class ;
   public string subject;
   public int id;
};  
The following program shows the use of the structure:
using System;
     
struct student
{
   public string name;
   public string aclass;
   public string subject;
   public int id;
};  

public class testStructure
{
   public static void Main(string[] args)
   {

     student student1;       
     student student2;       

      /* student1 detail */
      student1.name = "munesh";
      student1.class = "VI"; 
      student1.subject = "DOT Net programming";
      student1.id = 16;

      /* student 2 detail */
      student2.name = "rahul";
      student2.class = "VII";
      student2.subject =  "C programming";
      student2.id = 20;

      /* print student1 info */
      Console.WriteLine( "student 1 name : {0}", student1.name);
      Console.WriteLine("student1 class : {0}", student1.class);
      Console.WriteLine("student 1 subject : {0}", student1.subject);
      Console.WriteLine("student 1 Id :{0}", student1.id);

      /* print Book2 info */
      Console.WriteLine("student2 name : {0}", student2.name);
      Console.WriteLine("student 2 class : {0}", student2.class);
      Console.WriteLine("student2 subject : {0}", student2.subject);
      Console.WriteLine("student 2 id : {0}", student2.id);       

      Console.Readline();

   }
}
When the above code is compiled and executed, it produces the following result:
student 1 name : munesh
student 1 class : VI
student 1 subject : Dot Net Programming
student 1 id : 16
student 2 name : Rahul
student 2 class : VII
student 2 subject : C programming
student 2 id : 20


Class vs Structure go to this link

                                                                                 Previous....
                                                                                                                                    Next...... 

Enums in C#

                                                                                                                                                   Previous...
                                                                                                                                                        Next...


C# enumerations are value type.  An enumerated type is declared  the enum keyword.

Declaring enum keyword 

enum <enum_name> 
{ 
    enumeration list 
};
Where,
  • The enum_name specifies the enumeration type name.
  • The enumeration list is a comma-separated list of identifiers.
 enumeration stands for an integer value, one greater than the symbol that precedes it. By default, the value of the first enumeration symbol is 0. For example:
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };

Example:

The following example demonstrates use of enum variable:
using System;
namespace enumexample
{
   class EnumProgram
   {
      enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };

      static void Main(string[] args)
      {
         int WeekStart = (int)Days.Mon;
         int WeekEnd =   (int)Days.sunday;
         Console.WriteLine("Monday: {0}", WeekStart);
         Console.WriteLine("sunday: {0}", WeekEnd);
         Console.Readline();
      }
   }
}
result
Monday: 1
Friday: 7


                                                                                                                                                   Previous...
                                                                                                                                                        Next...

Friday, 7 February 2014

Polymorphism in C#

                                                                                                                                                Previous....

                                                                                                                                                     Next.....


The word polymorphism means having more then one forms. 
Polymorphism can be static or dynamic. In static polymorphism it is determined at the compile time. In dynamic polymorphism , it is decided at run-time.

Static Polymorphism/Function Overloading

It is an compile time polymorphism  because compiler already knows what type object it is linking to and waht type of method going to call. So linking a method at compiler time also called as early binding.
"In this Code method name same but its parameters are different  so it is called operate overloading."
using System;
namespace Polymorphism
{
   class calculation 
   {
      public int add(int a, int b)
      {
         return(a+b);
      }

      public int add(int a, int b,int c)

      {
         return(a+b+c);

      }

     }
Dynamic Polymorphism
It is an Run time polymorphism  because it is link at run time. So linking a method at run time also called as late binding.
"In this Code method name same and its parameters are also same  so it is called operate overriding."

In base class the method is declare "virtual" and in the derived class we override the same method. the virtual keyword indicate the method can be overridden in any derived class.
During run time, method overriding can be achieve by using inheritance principle and using "virtual" and "override" keyword.    
using System;
namespace employee
{
   public string firstname = "FN";
   public string secondname = "SN";

      public virtual void printfullname()
   console.writeline(firstname + " " + lastname);         }}

   public class parttime employee : employee
   {
      public override void printfullname()
      console.writeline("firstname + " " lastname + " parttime");  }}

      public class fulltimeemployee : employee
      {
         public override void printfullname()
        {
      console.writeline("firstname + " " lastname + " fullname");  }}
public class temporaryemployee : employee 
      { public override printfullname()
      { 
        console.writeline("firstname + " " lastname + " temporary ");  }}

         public class programme
      { public static void main()
   employee[] emp = new employee[4];
   emp [0] = new employee();
   emp [1] = new parttimeemployee();
   emp [2] = new fulltimeemployee();
   emp [3] = new tomporarytime employee();
   
     foreach(employee e in emp)

       {
         e.printfullname();
         
      }
   }
}
When the above code is compiled and executed, it produces the following result:
FN SN ,FN SN parttime

FN SN fulltime,FN SN temporary 
                                                                                                                                                                                              Previous....
                                                                                                                                                     Next.....

C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...