Monday, 5 March 2018

016 C# Events

Events
When we do a mouse click, press keyboard, move mouse, an event is generated .Other than mouse and keyboard, touch screen, joystick also generate events . Events are a kind of notification which system have to respond. When this kind of notification is generated, system need to perform some work as defined. 

                     For example, you are clicking on browser icon , 'click' generate some notification to the System, System find corresponding action with this notification, here System find that browser need to be open with this notification .System open the browser. 


 event handler is an object in a class, which raised an event with the help of the deligate . MSDN says that, there are two types of class. The class which is raising event, called publishers class. The class which is consuming the event is called subscriber class.It may also happened that a publisher class also consume events. 

Publishers Class : A class which contain delegates and even definition. A publisher class as a mapping of event and delegates, a publisher class also accountant mapping other object who is need to invoke. This object may be in the publisher class or outside the publisher class. 

Subscriber Class : publisher class invokes object of a subscriber class. 
Here is the syntax of event declaration . You should check event is Null before using any event.  an event is associated with an event Handler. An event and any event handler is declared in the same class. 

         Publisher class raise the event, subscriber class consume event. It may also occur that a event has no subscriber or event has multiple subscriber. When an event has multiple subscriber, method is called one by one synchronously. 

 An event can be defined with any of the access modifier.
  •  Public 
  •  Protected internal 
  •  internal 
  •  Private protected. 

The keyword can be applied on event is 
  • Static : static method are allowed to call anytime. 
  • Virtual: events allow inheritance, derived class property of base class.An event can be override 
  • Sealed : an event can be make non inheritable to the derived class. 
  • Abstract : an event can we make abstract, the derived class can have the same event.

When we declare an event in a class, it is associated with a delegate . Delegates and events both need to be declared in the class. Here is the example of event declaration. School class contain  a delicate declaration, named it StudentDelicate. An event is declared named StudentEvent is associated with the StudentDelicate .


class School
{
      
        public delegate void StudentDelegate();

        public event StudentDelegate StudentEvent;

}


Example 1
Here is the example of a publisher and subscriber class. Delegates and events are declared . The main method raise event GetFees is called.

//Subscriber Class
class Subscriber
{
      static void Main(string[] args)
      {
         Publisher obj = new Publisher();
         obj.StudentEvent += new Publisher.StudentDelegate(Example1);
         obj.GetFees();
      }

      static void Example1()
      {
       Console.WriteLine("Execute when event occure ");
      }
}

//Publisher Class
class Publisher
{
         public delegate void StudentDelegate();
         public event StudentDelegate StudentEvent;
         public void GetFees()
         {
           Console.WriteLine("Executed when Bind event and delegate");
        }
}

Example 2

 
class Publisher
{
          public static event StudentDelegate StudentEvent;

           static void Main(string[] args)
           {
             Subscriber obj = new Subscriber("Hellow World");
              StudentEvent += new StudentDelegate(obj.SubscriberEvent1);
              Process1();
            }
         public static void Process1()
         {
             System.Console.WriteLine("Process1 fired");
         }
}

public delegate void StudentDelegate();

class Subscriber
{
         string name;
         public Subscriber(string nameArg)
         {
            name = nameArg;
         }
        public void SubscriberEvent1()
       {
         System.Console.WriteLine("SubscriberEvent1 for object", name);
       }
}

021 C# Program Stucture

Program Stucture
You are going to write a simple program to get simple knowledge on C# program structure. To write a simple program we need to know about structure of  program. Here are the list of preliminary need to know before writing a simple program.

  •  namespace 
  •  method 
  •  function 
  •  comments multi line
  •  comments single line delete statement 
  •  class 
  •  main method

Below is a is the simple program of hello world. When you run this program, the program print the string "hello world" in the screen.

using System;
namespace student
{
         class student
         {
               public double Gatefees()
              {
                  double fees=300.65;
                  return fees;
             }
            static void main(string[] arg)
                  {
                      //Here is single line comments
                      /*Here is the exaple of 
                   multiline comments */
                   Console.WriteLine("hello world");
                }
      }
}
using system : system is a class at the root level. All other class of. Net comes under system class. System class is the namespace fundamental classes. The system namespace provides ,variable data type , like value type and reference type, event Handler, methods. using keyword tells the compiler, the component under system namespace will be available in this program. Generally a complex program have multiple using statement to include well namespace and functionality in it.

namespace student : namespace student keyword tells the compiler, class is declared under which namespace available only when this namespace is used. We have declared the class student, this will be available only, when a statement using student will be written at the top of the program. Namespace is a collection of classes, it can contain one or more classes. Here student is a namespace and student is the class under this namespace.

The next line is  a class declaration, a class is a template of an object. A class contain one or more method and variables. Here are student class accountant two method. The method, Gatefees will return the fees when it is called.

The main method is entry point of a program, when a program start running the main method is called fast.


Some points you should keep in mind
  •  C# is case sensitive 
  •  every C# statement ends with a semicolon 
  •  every C# program starts from A main method. 
  •  namespace must be included to get required component. The highest level of new namespace is system.

You have seen the hello world program,  now you will see how to create this program.

1) create project-->Empty project


2) a new project is created

3) add a c# source file ,Solution Explores-->Add-->New Item-- Code File-->> Name it student.cs

4)Write program in student.cs

5)Compile from built menu

6)Press F5

handling Syntax error : When a software engineer write program it is obvious that there will be some mistake on typing.. Net Framework is intelligent enough to report the error at the compile time. Engineer resolve the problem and compile again.. Net Framework is intelligence enough,it show possible resolution hints. Most of the time the hints works successfully and resolve the issue. But sometimes mislead the engineer in a wrong way.

C# keyword : Every language have some keyword to identify its features. This features active language structure. C# some keyword also. There are two type of Keyword reserve keyword and contextual keyword. Reserved keyword are the keywords that has been reserved by the C# own use. No variable, method, class can be declared with this name. Contextual keyword have some special meaning for some context, out of context this keyword can be used. Here is the list of some reserved keyword C#

Here is the list of reserved keyword by C#
 
 abstract  add  as  ascending
 async  await  base  bool
 break  by  byte  case
 catch  char  checked  class
 const  continue  decimal  default
 delegate  descending  do  double
 dynamic  else  enum  equals
 explicit  extern  false  finally
 fixed  float  for  foreach
 from  get  global goto
group  if  implicit  in
 int  interface  internal  into
 is  join  let  lock
 long  namespace  new  null
 object  on  operator  orderby
 out  override  params  partial
 private  protected  public  readonly
 ref  remove  return  sbyte
 sealed  select  set  short
 sizeof  stackalloc  static  string
 struct  switch  this  throw
 true  try  typeof  uint
 ulong  unchecked  unsafe  ushort
 using  value  var  virtual
 void  volatile  where  while
 yield




 Here is Some of contextual keyword by C#
  • add    
  • alias    
  • ascending
  • async    
  • await    
  • descending
  • dynamic    
  • from    
  • get






















018 C # tutorial Exception Handling

Exception handling :
You have written a program and successfully compile it. You have successfully tested your program also. During run time it may experience error. Even your code is fine, no Syntax error, testing also passed, still may error during run time. .Net provider structure for handling run time exception , this facility handle the error and continue the program without any obstacle.


try
         {
         }
catch
       {
       }
finally
      {
      }

                                              . Net exception handling comes under the namespace
System.Exception. All exception classes, maybe system define class or maybe custom class comes under the namespace System.Exception.
This facilates  
  •  A message to be human readable format.
  •  Tracing trace the particular point  from where the error  occured. 

An exception Handler have some particular method or area to handle the method. Any method or part of a method can throw exception, it may due to file access problem, divided by zero, variable not initialized and many more. Exception Handler syntax is as below.

Try : You have to put statement  of code in the try block . Try block wrap the code who is we need to associate any exception Handler. If any statement throw exception, the exception is thrown to the exception block in the method of "bubbling". If any error is occurred the handler will try to solve in the Handler, if not solve it will through the error again. Here is the example of try block.


try
    {
    //your code goes here
  }
Catch : The next part of an exception handler is catch block. Catch block works only when  any exception is occured  in the try block. In an exception Handler, there may be one or more catch block. Catch block will be written to handle the type of  exception need to be handled. There are several type of error can be occured. As we have discussed earlier there may be file access problem, divisible by zero problem.   So that ,the exception  may be of different type , null reference exception, argument null exception , divisible by zero exception. We can specify catch block to catch a specific exception. We can define our custom   user defined exception also. All this exception classes comes under the class System.exception. System.exception action will catch all the  exception of a program.

Example 1
try
           {
           //your code goes here
          }
catch(System.NullReferenceException e)
        {
         //Null Reference Handled
         }
catch (System.Exception ex)
       {
       //All exception
       }

Finally : Finally execute each time ,exception occured or not. Every code  goes through the try statement, will have to go through the final statement. We can  write  final block without catch block also. Here is the example of finally block.

Example 1
try
        {
         //your code goes here
        }
finally
        {
       }

Example 2
try
        {
         //your code goes here
        }
catch (System.ArgumentNullException e)
      {
      }
finally
     {
       //All Code Must be goes here
       //Execute All Time
   }


Nested Exception handler : Exception handler can be nested type also, a exception Handler contain another exception Handler. In this case , if the innermost exception handler fail to handle any error,  the immediate period will try to handle the error. Here is the example of nested exception Handler.



Example 1
try
        {
       //Nested Exception Handler
           try
              {
               //Your Statement
             }
            catch (System.ArgumentNullException e)
           {
           }
}
catch (System.Exception ex)
{
}
finally
{
         //All Code Must be goes here
         //Execute All Time
}


Custom exception or user defined exception : You can create a custom exception will the help of
System.ApplicationException class.  By inherit  System.ApplicationException exception class, a class will get all the required like message,  stack trace, inner exception properties etc. Now, you can custom you exception as required. Here is the example of custom exceptions.

 Example 1
public class MyCustom :System.ApplicationException

{

          public MyCustom(string message) : base(message)

           {

           }

}




try

       {


       }

catch (MyCustom ex)

     {

       Console.WriteLine("MyCustom: {0}", ex.Message);

    }

catch (Exception ep)

   {

   }

Rethrowing Exceptions : Writing an exception Handler is a tricky job, you may or may not catch and handle an exception in the  catch block. If an error is handled in catch block, then it is ok. Sometimes error cannot be handle in a particular catch blocks.  Then you need to exemption to handle outside of this catch block. Here is the example of throwing an exception when it is not handled by the catch blocks. While through throwing an exception, you can  pass additional information to the next application level.

Example 1
try
        {
        }
catch (System.ArgumentNullException e)
        {
         //Check if it can be handled
         throw e;
        }
finally
      {
      }
 Example2


try
        {
       }
catch (System.ArgumentNullException e)
     {
throw new NullReferenceException("I am getting error", e);
     }
finally
    {
   }
Here are some inbuilt exception class on .Net
  • System.IO.IOException : Handle file Input , Output error.
  • System.IndexOutOfRangeException : Handles array index out of range.
  • System.ArrayTypeMismatchException : Handles when type is mismatched with the array type.
  • System.NullReferenceException : Handles errors of null object.
  • System.DivideByZeroException : Handles errors when divided with zero.
  • System.InvalidCastException : Handles errors during typecasting.
  •  System.OutOfMemoryException : Handles errors of insufficient free memory.
  • System.StackOverflowException : Handles stack overflow error.  


Below are some example of exception handling of different type.
InvalidCastException  is a type of exception derived from System.Exception class. It handle error during the casting operation. The example shows that, you are converting Boolean to character which is impossible, the program is throwing error. The erroris is catched by InvalidCastException .

Example 1


bool flag = true;

try

        {

         char i = Convert.ToChar(flag);       

        }

       catch (InvalidCastException)

       {

          Console.WriteLine("Invalid cast from 'Boolean' to 'Char'");

      }

Example 1 
OutOfMemoryException  is a kind of exception which handle The error if out of memory occure . That is, there is no memory for the variable, and system is trying to access the memory Zone.The examples who's that String builder has in memory and we are going to insert extreme string position, and system is generating  exception.
StringBuilder sb = new StringBuilder(15, 15);

sb.Append("Hellow world");


try

   {

     sb.Insert(0, "I Am Learing C#", 1);

   }

  catch (OutOfMemoryException ex)

{

        Console.WriteLine("Out of Memory: {0}", ex.Message);

     //Insufficient memory to continue the execution of the program.

}


IndexOutOfRangeException  : a kind of exception , when is program access out of the the lower and upper bound range of an array. Below example array Range 100, program is trying to access 200 position. System is generating exception IndexOutOfRangeException
Example 1
try

       {

       int[] arr = new int[100];

       arr[0] = 1;

       arr[10] = 2;

       arr[200] = 3;

     }

catch (System.IndexOutOfRangeException ex)

    {

      //Index was outside the bounds of the array.

   }



বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...