Wednesday, December 20, 2006

System.Collections.Generic

Generic is a new feature introduced in C#. It is nothing but a type-safe collection. Generic collection can store only items that are compatible with argument type specified in declaration. Moreover generic collection works in similar way like non-generic collection, only the difference is to mixed types are not allowed. Non-generic collections are useful in case if you want to mix-up unrelated data types. List, Dictionary are example of C# generics.

Example:

using System;
using System.Collections.Generic;

class GenericDemo
{
public static void Main()
{
List lstInteger =new List();

//Add elements to generic integer list
//Correct entry as per generic
lstInteger.Add(1);
lstInteger.Add(2);
lstInteger.Add(3);
lstInteger.Add(4);
lstInteger.Add(5);


//Code exception due to following wrong entry
lstInteger.Add(‘Kuldeep’);
}
}


Because of type-safety principle, in above example it will throw error at last lstInteger.Add(‘Kuldeep’) statement. Current declaration for generic is an integer and at last statement you'r trying to insert is a string type. So it will raise exception.

Tuesday, December 19, 2006

The Mutex (C# - Threading)

Mutex is used to set exclusive access on shared resources in multi-thread programs. This means only one thread can access shared object at a time. A mutex is a perfect synchronization mechanism in C# threading.

Consider a example of when two threads accessing same system resources like files, system registry, Environment variables, etc. And you want to put exclusive access in multithreaded environment on shared resources then this can be achieved using mutex.

System.Thread.Mutex Class:

Above class supports Mutex.

To acquire Mutex call WaitOne()

To release Mutex call ReleaseMutex()

Example:

using System.Threading;

Mutex objMutex = new Mutex();

//Some code goes here

objMutex.WaitOne(); //Acquire

//Code to get exclusive access

//.....

objMutex.ReleaseMutex(); //Release

Mutex Code Snippet:

using System.Threading;

class FileAccess

{

public static Mutex mtx = new Mutex(); //Mutex variable

//Method to read/write in File

}

class FirstThread

{

public Thread t1;

//Uses above class method to R/W file

FirstThread()

{

t1= new Thread(this.CallFileWrite);

t1.Start();

}

void CallFileWrite()

{

FileAccess.mtx.WaitOne();

Console.WriteLine(“t1: In Mutex ”);

//File writing code ......

Console.WriteLine(“t1: Out Mutex ”);

FileAccess.mtx.ReleaseMutex();

}

}

}

class SecondThread

{

public Thread t2;

//Uses above class method to R/W file

SecondThread()

{

t2= New Thread(this.CallFileWrite);

t2.Start();

}

void CallFileWrite()

{

FileAccess.mtx.WaitOne();

Console.WriteLine(“t2: In Mutex ”);

//File writing code ...... for same file in t1 thread

Console.WriteLine(“t2: Out Mutex ”);

FileAccess.mtx.ReleaseMutex();

}

}

class MutexExample

{

void main()

{

FirstThread mFt1 = new FirstThread();

SecondThread mSt2 = new SecondThread();

MFt1.t1.Join();

MSt2.t2.Join();

}

}

Exception Handling in C#

Exception class is used to handle errors occurred during execution of code. Following are public members of exception class:

HelpLink : Used to set help link for exception.

InnerException: Gets the exception instance that caused the current exception.

Message: Exception description.

Source: Object that caused exception

StackTrace: Call stack for occurred exception.

TargetSite: Method that throws the exception.

Simple exception handling code block:

try

{

// Code statements.

}

catch(Type x)

{

// handling of the exception

}

finally

{

//cleanup code (if any)

}

Note: Catch block is optional in C#. And Finally block always execute.

Multiple Catch Blocks: (All good Programs must be able to uniformly handle errors that occur during code execution.)

try

{

//Your code goes here

}

catch(DivideByZeroException dz)

{

//Divide by zero exceptions will be handled here.

}

catch(OutOfMemoryException oe)

{

//Out of memory exceptions will be handled here.

}

catch(NullReferenceException ee)

{

//Null refernce exceptions will be handled here.

}

catch(Exception ex)

{

//Unknown exceptions from above 3 types will be handled here.

}

finally

{

//Always executes at the end.

}

Some Other Exception types:

IndexOutOfRangeException (Occures in looping when Index is out of range)

InvalidOperationException (Thrown by methods when in an invalid state.)

ArgumentNullException (Thrown by methods that do not allow an argument to be null.)

ComException (COM components)

InvalidCastException

ArithmeticException

SqlException (For DB related exceptions)

ApplicationException Class:

If you are designing an application that needs to create its own exceptions, derive from the ApplicationException class. ApplicationException extends Exception class.

To know more about structured and ApplicatioException handling goto http://www.devcity.net/Articles/284/1/article.aspx (This is supported by Microsoft)

Best practices to handling exceptions:

URL:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconbestpracticesforhandlingexceptions.asp

Visitor Count: