Wednesday, 13 March 2013

Exceptions in C#

When we write a program there are chances of coming across 2 different types of errors
  • Compile-time Errors
  • Run-time Errors.
An error which comes into picture at the time of program compilation is a compile-time error which may occur due to syntax mistakes. An error which occurs in the middle of the programs execution is known as a run-time error and these errors occur due to various reasons like wrong implementation of logic, wrong inputs supplied to a program, missing of required resources etc. 
A compile-time error is not dangerous because it occurs at the time of compilation whereas run-time errors are dangerous because they occur in the program when the execution is going on and if at all a run-time error occurs in a program, the program terminates abnormally on the same line where the error gets occured without executing the rest of the code.

Note:  Whenever an error situation occurs in a program the exception handler comes into picture to identify the type of error and then creates an object of an exception class associated with that error and throws that object and that object will first terminate the program abnormally and then displays an error message associated with an exception object.

Exception Handling

Whenever a run- time error occurs under the program abnormal termination is occuring so we will be facing so many problems in the application. To overcome the problems we are provided with a mechanism known as Exception Handling.

Exception Handling is a process of stopping the abnormal termination of the program whenever the exceptions are terminating the program in case of run time error. If we can stop the abnormal termination of a program we will be getting following advantages :
  • We can make the statement which are not associated with the error.
  • We can display a user friendly error message to the end user so that he can resolve the error, got occurred provided if it is in his hands.
  • We can also perform some corrective actions to come out of a problems that may occur due to error.
To handle an exception we need to enclose our code under some special blocks known as try catch block which should be used as following:

try
{
-statements which requires execution when the run time error occurs.
-statements which does not require execution only when the run time error occurs.
}
catch
{
-statements which requires execution only when the run time error occurs.
}
[--< multiple catch blocks if required >--]

Add a class Exception demo.cs and write the following code:


using System;

namespace CSharpConsole
{
    class ExceptionDemo
    {
        static void Main()
        {
            int x, y, z;
            try
            {
                Console.WriteLine("Enter x value: ");
                x = int.Parse(Console.ReadLine());

                Console.WriteLine("Enter y value: ");
                y = int.Parse(Console.ReadLine());

                z = x / y;
                Console.WriteLine(z);
            }
            catch (DivideByZeroException ex1) //ex1 is a variable of class          DivideByZeroException
            {
                Console.WriteLine("Divisor must not be zero");
            }
            catch (FormatException ex2) //ex2 is a variable of class FormatException
            {
                Console.WriteLine("Input must be numeric");
            }

            catch (Exception ex3)
            {
                Console.WriteLine(ex3.Message);//message is a read only property
            }
            {
                Console.WriteLine("End of the program");
                Console.ReadLine();
            }
         }
    }
}

Tuesday, 12 March 2013

Types of Delegates

Delegates are of two types:
  • Unicast Delegate
  • Multicast Delegate
If a delegate is used for calling a single method we call it as a unicast delegate whereas if a delegate is use for calling multiple methods its a multicast delegate.
In case of the methods delegate, a single delegate call will execute all the methods that are bound with the delegate.
using System;

namespace CSharpConsole
{
    public  delegate void MathDel(int x, int y);
    class DelMulti
    {
        public void Add(int x, int y)
        {
            Console.WriteLine("Add:  " + (x + y));
        }
        public void Sub(int x, int y)
        {
            Console.WriteLine("Sub:  " + (x - y));
        }
        public void Mul(int x, int y)
        {
            Console.WriteLine("mul:  " + (x * y));
        }
        public void Div(int x, int y)
        {
            Console.WriteLine("Div:  " + (x / y));
        }
        static void Main()
        {
            DelMulti obj = new DelMulti();
            MathDel md=new MathDel (obj.Add );
            md+=obj.Sub ;md +=obj.Mul ;md +=obj.Div ;
            md(100,25);
            Console .WriteLine ();
            md(600,30);
            Console .WriteLine ();
            md -=obj.Mul ;
            md(450,50);
            Console .ReadLine ();
            
        }

    }
}
 

 

Delegates in C#

It is also an user defined type which is used for invoking or calling the methods of a class.

A method that is defined under a class can be called in 2 different ways
  • With the help of object of a class if it is non static or name of a class if it is static.
  • By using the delegate also we can call  the method of a class even if it is static or non static.
Note: Calling the method in the 1st process is different than calling the method in the 2nd process.

Calling a method using a Delegate

       If we want to call a method using a delegate we need to adopt the following process
  • Defining a delegate:   
[<modifiers>] delegate <void/type> <Name> ([<Parameter Definition's>])

The definition of a delegate is similar to a method definition where a method will have body whereas a delegate will not have any body where we use these delegates for calling these methods.

Note: While defining a delegate make sure the I/O parameters of Delegates are same as the I/O parameters of the method we want to call with the help of a delegate.
  • As the delegate is a type, after defining a delegate to consume it we need to create an object of it and while creating the object, the method we want to call using the delegate should be passed as a parameter to the delegates constructor.
  • Now call the delegate by passing the required parameter value so that the method gets executed internally.

Delegate Example


using System;
namespace CSharpConsole
{
    class DelDemo
    {
        public void Add(int x, int y)
        {
            Console.WriteLine(x + y);
        }
        public static string SayHello(string name)
        {
            return "Hello " + name;
        }
        public delegate void AddDel(int a, int b);
        public delegate string SayDel(string name);

        static void Main()
        {
            DelDemo obj = new DelDemo();
            AddDel ad = new AddDel(obj.Add);
            SayDel  sd = new SayDel (DelDemo.SayHello);
            ad(100, 50); ad(234, 434); ad(672, 157);
            Console.WriteLine(sd("AAA"));
            Console.WriteLine(sd("BBB"));
            Console.WriteLine(sd("CCC"));
            Console.ReadLine();
                   
        }
    }
}

Monday, 11 March 2013

Indexers in Csharp

These are also use for providing access to the values of the class outside of the class outside of the class like a property but provides access to a value with the specific name but indexers provides access to the value with the object of a class using index positions just like an array.
We define indexers in a class as following:

 Syntax:
[<modifiers>]<type> this [int index or srting name]
{
[get{<statements>}]
[set{<statements>}] 
}

Indexers are defined very much similar to properties but an indexer doesn't have any name. In the place of name we use the 'this' keyword which means we are definning an indexer object of that class starts providing access to the values that are present inside the class, either with the help  of index or name.

Add a class Employee.cs and write the following code:

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

namespace CSharpConsole
{
    class Employee
    {
        int _Empno;
        string _Ename, _Job;
        double _Salary;
        public Employee(int Empno)
        {
            this._Empno = Empno;
            this._Ename = "Leena";
            this._Job = "Developer";
            this._Salary = 5000;
        }
        public object this[int index] // accessing by 'index' 
        {  
            //read/wrtie properties with conditions
            get
            {
                if (index == 0)
                    return _Empno;
                else if (index == 1)
                    return _Ename;
                else if (index == 2)
                    return _Job;
                else if (_Salary == 3)
                    return _Salary;
                return null;
            }
            //read/write properties with conditions
            set
            {
                if (index == 1)
                    _Ename = value.ToString();
                else if (index == 2)
                    _Job = value.ToString();
                else if(index==3)
                    _Salary =(Convert.ToDouble(value));
            }
        }
        public object this[string name]   //accessing by'name'
        {
            get
            {
                if (name == "Empno")
                    return _Empno;
                else if (name == "Ename")
                    return _Ename;
                else if (name == "Job")
                    return _Job;
                else if (name == "Salary")
                    return _Salary;
                return null;
            }
            set
            {
                if (name == "Ename")
                    _Ename = value.ToString();
                else if (name == "Job")
                    _Job = value.ToString();
                else if (name == "Salary")
                    _Salary = Convert.ToDouble(value);

            }
        }
    }
}
Add another class TestEmployee.cs and write the following code:
using System;

namespace CSharpConsole
{
    class TestEmployee
    {
        static void Main()
        {
            Employee emp = new Employee(1001);
            Console.WriteLine(emp[0]);
            Console .WriteLine (emp [1]);
            Console.WriteLine(emp[2]);
            Console.WriteLine(emp[3]);
            
            // Assigning a new value
            emp[1] = "Cheryl";
            emp["Ename"] = "BA";
            emp[3] = 8000;

            Console.WriteLine(emp["Empno"]);
            Console.WriteLine(emp["Ename"]);
            Console.WriteLine(emp["Job"]);
            Console.WriteLine(emp["Salary"]);
            Console.ReadLine();
        }
    }
}

First outing in Hyderabad with friends!!

     Finally, for the 1st time in 2 months we roamed in Hyderabad. I, along with my room mates went to NTR garden on Saturday. Actually we had planned to go to Lumbini Garden but unfortunately it was closed because of the trouble going on in Hyderabad. So then we finally went to NTR, We went around 3 in the afternoon and returned around 8 at night. We thoroughly enjoyed ourselves.
     Now back to the task which sudeep gave us. Sudeep had told me to do some updations such as some validations, to be able to edit, delete and add new courses at runtime etc. I am still working on it and I hope to finish it as soon s possible.