मंगलवार, 8 नवंबर 2016

Simple way of C# :part 5

1. EXCEPTION HANDLING
An exception is a problem that arises during the execution of a program. A C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. C# exception handling is built upon four keywords: try, catch, finally, and throw.
try: A try block identifies a block of code for which particular exceptions is activated. It is 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
{
// statements causing exception
}
catch( ExceptionName e1 )
{
// error handling code
}
catch( ExceptionName e2 )
{

// error handling code
}
catch( ExceptionName eN )
{
// error handling code
}
finally
{
// statements to be executed
}
========================================================
You can list down multiple catch statements to catch different type of exceptions in case your try block raises more than one exception in different situations.

Exception Classes in C# :
C# exceptions are represented by classes. The exception classes in C# are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException classes.
The System.ApplicationException class supports exceptions generated by application programs. Hence the exceptions defined by the programmers should derive from this class.
The System.SystemException class is the base class for all predefined system exception.

The following table provides some of the predefined exception classes derived from the Sytem.SystemException class:
1 System.IO.IOException : Handles I/O errors.
2 System.IndexOutOfRangeException : Handles errors generated when a method                     refers to an array index out of range.
3 System.ArrayTypeMismatchException :  Handles errors generated when type is           mismatched with the array type.
4 System.NullReferenceException : Handles errors generated from deferencing a null     object.
5 System.DivideByZeroException : Handles errors generated from dividing a                     dividend with zero.
6 System.InvalidCastException : Handles errors generated during typecasting.
7 System.OutOfMemoryException : Handles errors generated from insufficient free          memory.
8 System.StackOverflowException : Handles errors generated from stack overflow.

Handling Exceptions :
C# provides a structured solution to the exception handling in the form of try and catch blocks. Using these blocks the core program statements are separated from the error-handling statements.
Example : 

using System;
namespace ErrorHandlingApplication
{
class DivNumbers
{
int result;
DivNumbers()
{
result = 0;
}
public void division(int num1, int num2)

{
try
{
result = num1 / num2;
}
catch (DivideByZeroException e)
{
Console.WriteLine("Exception caught: {0}", e);
}
finally
{
Console.WriteLine("Result: {0}", result);
}
}
static void Main(string[] args)
{
DivNumbers d = new DivNumbers();
d.division(25, 0);
Console.ReadKey();
}
}

}
===============================================
When the above code is compiled and executed, it produces the following result:
Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at ...

Result: 0

Creating User-Defined Exceptions :
You can also define your own exception. User-defined exception classes are derived from the ApplicationException class. The following example demonstrates this:

using System;
namespace UserDefinedException
{
class TestTemperature
{
static void Main(string[] args)
{
Temperature temp = new Temperature();
try
{
temp.showTemp();
}
catch(TempIsZeroException e)
{
Console.WriteLine("TempIsZeroException: {0}", e.Message);
}
Console.ReadKey();
}
}
}
public class TempIsZeroException: ApplicationException
{
public TempIsZeroException(string message): base(message)
{
}
}
public class Temperature
{
int temperature = 0;
public void showTemp()
{
if(temperature == 0)
{
throw (new TempIsZeroException("Zero Temperature found"));
}
else
{
Console.WriteLine("Temperature: {0}", temperature);
}
}
}
=================================================
When the above code is compiled and executed, it produces the following result:
TempIsZeroException: Zero Temperature found

Throwing Objects :
You can throw an object if it is either directly or indirectly derived from the System.Exception class. You can use a throw statement in the catch block to throw the present object as:
Catch(Exception e)
{
...
Throw e
}

2 .FILE I/O
A file is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a stream.

The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the input stream and the output stream. The input stream is used for reading data from file (read operation) and the output stream is used for writing into the file (write operation).
C# I/O Classes :
The System.IO namespace has various classes that are used for performing numerous operations with files, such as creating and deleting files, reading from or writing to a file, closing a file etc.
The following table shows some commonly used non-abstract classes in the System.IO namespace:

1 BinaryReader : Reads primitive data from a binary stream.
2 BinaryWriter : Writes primitive data in binary format.
3 BufferedStream : A temporary storage for a stream of bytes.
4 Directory : Helps in manipulating a directory structure.
5 DirectoryInfo : Used for performing operations on directories.
6 DriveInfo : Provides information for the drives.
7 File : Helps in manipulating files.
8 FileInfo : Used for performing operations on files.
9 FileStream : Used to read from and write to any location in a file.
10 MemoryStream :
Used for random access to streamed data stored in memory.
11 Path : Performs operations on path information.
12 StreamReader : Used for reading characters from a byte stream.
13 StreamWriter : Its used for writing characters to a stream.
14 StringReader :  Its used for reading from a string buffer.
15 StringWriter : Its used for writing into a string buffer.

The FileStream Class :
The FileStream class in the System.IO namespace helps in reading from, writing to and closing files. This class derives from the abstract class Stream.
You need to create a FileStream object to create a new file or open an existing file. The syntax for creating a FileStream object is as follows:

FileStream <object_name> = new FileStream( <file_name>,
<FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>);

For example, we create a FileStream object F for reading a file named sample.txt as shown:

FileStream F = new FileStream("sample.txt", FileMode.Open, FileAccess.Read, FileShare.Read);

Parameter : 
1 FileMode
The FileMode enumerator defines various methods for opening files. The members of the FileMode enumerator are:
 Append:  It opens an existing file and puts cursor at the end of file, or creates                the file, if the file does not exist.
 Create:  It creates a new file.
 CreateNew:  It specifies to the operating system, that it should create a new file.
 Open:  It opens an existing file.
 OpenOrCreate: It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file.

 Truncate: It opens an existing file and truncates its size to zero bytes.

2 FileAccess
FileAccess enumerators have members: Read, ReadWrite and Write.

3 FileShare
FileShare enumerators have the following members:
 Inheritable: It allows a file handle to pass inheritance to the child processes.
 None: It declines sharing of the current file.
 Read: It allows opening the file for reading.
 ReadWrite: It allows opening the file for reading and writing.
 Write: It allows opening the file for writing.

Example : 
The following program demonstrates use of the FileStream class:

using System;
using System.IO;
namespace FileIOApplication
{
class Program
{
static void Main(string[] args)
{
FileStream F = new FileStream("test.dat",
FileMode.OpenOrCreate, FileAccess.ReadWrite);
for (int i = 1; i <= 20; i++)
{
F.WriteByte((byte)i);
}
F.Position = 0;
for (int i = 0; i <= 20; i++)
{
Console.Write(F.ReadByte() + " ");
}
F.Close();
Console.ReadKey();
}
}
}
===============================================
When the above code is compiled and executed, it produces the following result:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1

Advanced File Operations in C# :
The preceding example provides simple file operations in C#. However, to utilize the immense powers of C# System.IO classes, you need to know the commonly used properties and methods of these classes.
1 Reading from and Writing into Text files It involves reading from and writing into text files. The StreamReader and StreamWriterclass helps to accomplish it.
2 Reading from and Writing into Binary files It involves reading from and writing into binary files. The BinaryReader andBinaryWriter class helps to accomplish this.
3 Manipulating the Windows file system It gives a C# programamer the ability to browse and locate Windows files and directories.

The StreamReader Class :
The StreamReader class also inherits from the abstract base class TextReader that represents a reader for reading series of characters. The following table describes some of the commonly used methods of the StreamReader class:

1 public override void Close() : It closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader.
public override int Peek() : Returns the next available character but does not consume it.
public override int Read() : Reads the next character from the input stream and advances the character position by one.

Example : 
using System;
using System.IO;
namespace FileApplication
{
class Program
{
static void Main(string[] args)
{
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("c:/jamaica.txt"))
{
string line;
// Read and display lines from the file until
// the end of the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.

Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}

}
==================================================
The StreamWriter Class :
The StreamWriter class inherits from the abstract class TextWriter that represents a writer, which can write a series of character.

The following table describes the most commonly used methods of this class:
public override void Close() : Closes the current StreamWriter object and the underlying stream.
public override void Flush() :  Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.
public virtual void Write(bool value) : Writes the text representation of a Boolean value to the text string or stream.(Inherited from TextWriter.)
public override void Write( char value ) : Writes a character to the stream.
public virtual void Write( decimal value ) : Writes the text representation of a decimal value to the text string or stream.
6 public virtual void Write( double value ) : Writes the text representation of an 8-byte floating-point value to the text string or stream.
public virtual void Write( int value ) : Writes the text representation of a 4-byte signed integer to the text string or stream.
public override void Write( string value ) : Writes a string to the stream.
public virtual void WriteLine() : Writes a line terminator to the text string or stream.

Example : 
The following example demonstrates writing text data into a file using the StreamWriter class:

using System;
using System.IO;
namespace FileApplication
{
class Program
{
static void Main(string[] args)
{
string[] names = new string[] {"RAJ KUMAR", "RAJ  KUMARS"};
using (StreamWriter sw = new StreamWriter("names.txt"))

{
foreach (string s in names)
{
sw.WriteLine(s);
}
}
// Read and show each line from the file.
string line = "";
using (StreamReader sr = new StreamReader("names.txt"))
{
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
Console.ReadKey();
}
}
}
=============================================
When the above code is compiled and executed, it produces the following result:
RAJ KUMAR

RAJ KUMARS

Reading from and Writing into Binary files :
The BinaryReader and BinaryWriter classes are used for reading from and writing to a binary file.
The BinaryReader Class :
The BinaryReader class is used to read binary data from a file. A BinaryReader object is created by passing a FileStream object to its constructor.
public override void Close() : It closes the BinaryReader object and the underlying stream.
public virtual int Read() : Reads the characters from the underlying stream and advances the current position of the stream.
public virtual bool ReadBoolean() : Reads a Boolean value from the current stream and advances the current position of the stream by one byte.
public virtual byte ReadByte() : Reads the next byte from the current stream and advances the current position of the stream by one byte.
public virtual byte[] ReadBytes( int count ) : Reads the specified number of bytes from the current stream into a byte array and advances the current position by that number of bytes.
public virtual char ReadChar() : Reads the next character from the current stream and advances the current position of the stream in accordance with the Encoding used and the specific character being read from the stream.
public virtual char[] ReadChars( int count ) : Reads the specified number of characters from the current stream, returns the data in a character array, and advances the current position in accordance with the Encoding used and the specific character being read from the stream.
public virtual double ReadDouble() : Reads an 8-byte floating point value from the current stream and advances the current position of the stream by eight bytes.
public virtual int ReadInt32() : Reads a 4-byte signed integer from the current stream and advances the current position of the stream by four bytes.
10 public virtual string ReadString() :Reads a string from the current stream. The string is prefixed with the length, encoded as an integer seven bits at a time.

The BinaryWriter Class :
The BinaryWriter class is used to write binary data to a stream. A BinaryWriter object is created by passing a FileStream object to its constructor.
public override void Close() 
It closes the BinaryWriter object and the underlying stream.
public virtual void Flush() 
Clears all buffers for the current writer and causes any buffered data to be written to the underlying device.
public virtual long Seek( int offset, SeekOrigin origin )
Sets the position within the current stream.
public virtual void Write( bool value )
Writes a one-byte Boolean value to the current stream, with 0 representing false and 1 representing true.
public virtual void Write( byte value )
Writes an unsigned byte to the current stream and advances the stream position by one byte.
public virtual void Write( byte[] buffer )
Writes a byte array to the underlying stream.
public virtual void Write( char ch )
Writes a Unicode character to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream.
public virtual void Write( char[] chars )
Writes a character array to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream.
public virtual void Write( double value )
Writes an eight-byte floating-point value to the current stream and advances the stream position by eight bytes.
10 public virtual void Write( int value )
Writes a four-byte signed integer to the current stream and advances the stream position by four bytes.
11 public virtual void Write( string value )
Writes a length-prefixed string to this stream in the current encoding of the BinaryWriter, and advances the current position of the stream in accordance with the encoding used and the specific characters being written to the stream.

Example : 
The following example demonstrates reading and writing binary data:
using System;
using System.IO;
namespace BinaryFileApplication
{
class Program
{
static void Main(string[] args)
{
BinaryWriter bw;
BinaryReader br;
int i = 25;
double d = 3.14157;
bool b = true;
string s = "I am happy";
//create the file
try
{
bw = new BinaryWriter(new FileStream("mydata",
FileMode.Create));
}
catch (IOException e)
{
Console.WriteLine(e.Message + "\n Cannot create file.");
return;
}
//writing into the file
try
{
bw.Write(i);
bw.Write(d);
bw.Write(b);
bw.Write(s);
}
catch (IOException e)

{
Console.WriteLine(e.Message + "\n Cannot write to file.");
return;
}
bw.Close();
//reading from the file
try
{
br = new BinaryReader(new FileStream("mydata",
FileMode.Open));
}
catch (IOException e)
{
Console.WriteLine(e.Message + "\n Cannot open file.");
return;
}
try
{
i = br.ReadInt32();
Console.WriteLine("Integer data: {0}", i);
d = br.ReadDouble();
Console.WriteLine("Double data: {0}", d);
b = br.ReadBoolean();
Console.WriteLine("Boolean data: {0}", b);
s = br.ReadString();
Console.WriteLine("String data: {0}", s);
}
catch (IOException e)

{
Console.WriteLine(e.Message + "\n Cannot read from file.");
return;
}
br.Close();
Console.ReadKey();
}
}

}
=================================================

The DirectoryInfo Class :

The DirectoryInfo class is derived from the FileSystemInfo class. It has various methods for creating, moving, and browsing through directories and subdirectories. This class cannot be inherited.
1 Attributes : Gets the attributes for the current file or directory.
CreationTime : Gets the creation time of the current file or directory.
Exists : Gets a Boolean value indicating whether the directory exists.
Extension : Gets the string representing the file extension.
FullName : Gets the full path of the directory or file.
LastAccessTime : Gets the time the current file or directory was last accessed.
Name : Gets the name of this DirectoryInfo instance.

Following are some commonly used methods of the DirectoryInfo class:
public void Create() : Creates a directory.
public DirectoryInfo CreateSubdirectory( string path ) : Creates a subdirectory or subdirectories on the specified path. The specified path can be relative to this instance of the DirectoryInfo class.
public override void Delete() : Deletes this DirectoryInfo if it is empty.
public DirectoryInfo[] GetDirectories() : Returns the subdirectories of the current directory.
public FileInfo[] GetFiles() : Returns a file list from the current directory.

The FileInfo Class :
The FileInfo class is derived from the FileSystemInfo class. It has properties and instance methods for creating, copying, deleting, moving, and opening of files, and helps in the creation of FileStream objects. This class cannot be inherited.
Following are some commonly used properties of the FileInfo class:
Attributes : Gets the attributes for the current file.
CreationTime : Gets the creation time of the current file.
Directory : Gets an instance of the directory which the file belongs to.
Exists : Gets a Boolean value indicating whether the file exists.
Extension : Gets the string representing the file extension.
FullName : Gets the full path of the file.
LastAccessTime : Gets the time the current file was last accessed.
LastWriteTime : Gets the time of the last written activity of the file.
Length : Gets the size, in bytes, of the current file.
10 Name : Gets the name of the file.

Following are some commonly used methods of the FileInfo class:
public StreamWriter AppendText() : Creates a StreamWriter that appends text to the file represented by this instance of the FileInfo.
public FileStream Create() : Creates a file.
public override void Delete() : Deletes a file permanently.
public void MoveTo( string destFileName ) : Moves a specified file to a new location, providing the option to specify a new file name.
public FileStream Open( FileMode mode ) : Opens a file in the specified mode.
public FileStream Open( FileMode mode, FileAccess access ) : Opens a file in the specified mode with read, write, or read/write access.
public FileStream Open( FileMode mode, FileAccess access, FileShare share ) :
 Opens a file in the specified mode with read, write, or read/write access and the specified sharing option.
public FileStream OpenRead() : Creates a read-only FileStream
public FileStream OpenWrite() : Creates a write-only FileStream.

Example : 
The following example demonstrates the use of the above-mentioned classes:

using System;
using System.IO;
namespace WindowsFileApplication
{
class Program
{
static void Main(string[] args)
{
//creating a DirectoryInfo object
DirectoryInfo mydir = new DirectoryInfo(@"c:\Windows");
// getting the files in the directory, their names and size
FileInfo [] f = mydir.GetFiles();
foreach (FileInfo file in f)
{
Console.WriteLine("File Name: {0} Size: {1}",
file.Name, file.Length);
}
Console.ReadKey();
}
}

}
==================================================

3. ATTRIBUTES
An attribute is a declarative tag that is used to convey information to runtime about the behaviors of various elements like classes, methods, structures, enumerators, assemblies etc. in your program. You can add declarative information to a program by using an attribute. A declarative tag is depicted by square ([ ]) brackets placed above the element it is used for.

Attributes are used for adding metadata, such as compiler instruction and other information such as comments, description, methods and classes to a program. The .Net Framework provides two types of attributes: the pre-defined attributes and custom builtattributes.
Syntax for specifying an attribute is as follows:

[attribute(positional_parameters, name_parameter = value, ...)]
element

Predefined Attributes :

The .Net Framework provides three pre-defined attributes:
AttributeUsage :
The pre-defined attribute AttributeUsage describes how a custom attribute class can be used. It specifies the types of items to which the attribute can be applied.
Syntax for specifying this attribute is as follows:
[AttributeUsage(
validon,
AllowMultiple=allowmultiple,
Inherited=inherited

)]
The parameter validon specifies the language elements on which the attribute can be placed. It is a combination of the value of an enumerator AttributeTargets. The default value is AttributeTargets.All.
 The parameter allowmultiple (optional) provides value for the AllowMultipleproperty of this attribute, a Boolean value. If this is true, the attribute is multiuse. The default is false (single-use).

 The parameter inherited (optional) provides value for the Inherited property of this attribute, a Boolean value. If it is true, the attribute is inherited by derived classes. The default value is false (not inherited).

Conditional :
This predefined attribute marks a conditional method whose execution depends on a specified preprocessing identifier.

It causes conditional compilation of method calls, depending on the specified value such as Debug or Trace. For example, it displays the values of the variables while debugging a code.
Syntax for specifying this attribute is as follows:
[Conditional(
conditionalSymbol
)]

The following example demonstrates the attribute:

#define DEBUG
using System;
using System.Diagnostics;
public class Myclass
{
[Conditional("DEBUG")]
public static void Message(string msg)
{
Console.WriteLine(msg);
}
}
class Test
{
static void function1()
{
Myclass.Message("In Function 1.");
function2();
}
static void function2()
{
Myclass.Message("In Function 2.");
}
public static void Main()
{
Myclass.Message("In Main function.");
function1();
Console.ReadKey();
}
}
================================================

Obsolete :
This predefined attribute marks a program entity that should not be used. It enables you to inform the compiler to discard a particular target element. For example, when a new method is being used in a class and if you still want to retain the old method in the class, you may mark it as obsolete by displaying a message the new method should be used, instead of the old method.

Syntax for specifying this attribute is as follows:
[Obsolete(
message
)]
[Obsolete(
message,
iserror
)]
Where,
 The parameter message, is a string describing the reason why the item is obsolete and what to use instead.

 The parameter iserror, is a Boolean value. If its value is true, the compiler should treat the use of the item as an error. Default value is false (compiler generates a warning).
The following program demonstrates this:

using System;
public class MyClass
{
[Obsolete("Don't use OldMethod, use NewMethod instead", true)]
static void OldMethod()
{
Console.WriteLine("It is the old method");
}
static void NewMethod()
{
Console.WriteLine("It is the new method");
}
public static void Main()
{
OldMethod();
}
}
==============================================
When you try to compile the program, the compiler gives an error message stating:

Don't use OldMethod, use NewMethod instead

Creating Custom Attributes :
The .Net Framework allows creation of custom attributes that can be used to store declarative information and can be retrieved at run-time. This information can be related to any target element depending upon the design criteria and application need.
Creating and using custom attributes involve four steps:
1. Declaring a custom attribute
2. Constructing the custom attribute
3. Apply the custom attribute on a target program element
4. Accessing Attributes Through Reflection

The Last step involves writing a simple program to read through the metadata to find various notations. Metadata is data about data or information used for describing other data. This program should use reflections for accessing attributes at runtime.
Declaring a Custom Attribute :
A new custom attribute should is derived from the System.Attribute class. For example,
//a custom attribute BugFix to be assigned to a class and its members
[AttributeUsage(AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]
public class DeBugInfo : System.Attribute

Constructing the Custom Attribute :
Let us construct a custom attribute named DeBugInfo, which stores the information obtained by debugging any program. Let it store the following information:
 The code number for the bug
 Name of the developer who identified the bug
 Date of last review of the code
 A string message for storing the developer's remarks
The DeBugInfo class has three private properties for storing the first three information and a public property for storing the message. Hence the bug number, developer’s name, and date of review are the positional parameters of the DeBugInfo class and the message is an optional or named parameter.

Each attribute must have at least one constructor. The positional parameters should be passed through the constructor.
//a custom attribute BugFix to be assigned to a class and its members
[AttributeUsage(AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]
public class DeBugInfo : System.Attribute
{
private int bugNo;
private string developer;
private string lastReview;
public string message;
public DeBugInfo(int bg, string dev, string d)
{
this.bugNo = bg;
this.developer = dev;
this.lastReview = d;
}
public int BugNo
{
get
{
return bugNo;
}
}
public string Developer
{
get
{

return developer;
}
}
public string LastReview
{
get
{
return lastReview;
}
}
public string Message
{
get
{
return message;
}
set
{
message = value;
}
}

}
=========================================================

4. REFLECTION
Reflection objects are used for obtaining type information at runtime. The classes that give access to the metadata of a running program are in the System.Reflection namespace.

The System.Reflection namespace contains classes that allow you to obtain information about the application and to dynamically add types, values, and objects to the application.
Applications of Reflection :
Reflection has the following applications:
 It allows view attribute information at runtime.
 It allows examining various types in an assembly and instantiate these types.
 It allows late binding to methods and properties
 It allows creating new types at runtime and then performs some tasks using those types.

Viewing Metadata :
We have mentioned in the preceding chapter that using reflection you can view the attribute information.
The MemberInfo object of the System.Reflection class needs to be initialized for discovering the attributes asscociated with a class. To do this, you define an object of the target class, as:
System.Reflection.MemberInfo info = typeof(MyClass);

The following program demonstrates this:

using System;
[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute
{

public readonly string Url;
public string Topic // Topic is a named parameter
{
get
{
return topic;
}
set
{
topic = value;
}
}
public HelpAttribute(string url) // url is a positional parameter
{
this.Url = url;
}
private string topic;
}
[HelpAttribute("Information on the class MyClass")]
class MyClass
{
}
namespace AttributeAppl
{

class Program
{
static void Main(string[] args)
{
System.Reflection.MemberInfo info = typeof(MyClass);
object[] attributes = info.GetCustomAttributes(true);
for (int i = 0; i < attributes.Length; i++)
{
System.Console.WriteLine(attributes[i]);
}
Console.ReadKey();
}
}
}
==================================================
When it is compiled and run, it displays the name of the custom attributes attached to the class MyClass:

HelpAttribute

5. PROPERTIES
Properties are named members of classes, structures, and interfaces. Member variables or methods in a class or structures are called Fields. Properties are an extension of fields and are accessed using the same syntax. They use accessors through which the values of the private fields can be read, written, or manipulated.
Properties do not name the storage locations. Instead, they have accessors that read, write, or compute their values.

For example, let us have a class named Student, with private fields for age, name, and code. We cannot directly access these fields from outside the class scope, but we can have properties for accessing these private fields.
Accessors :
The accessor of a property contains the executable statements that helps in getting (reading or computing) or setting (writing) the property. The accessor declarations can contain a get accessor, a set accessor, or both.

Example
The following example demonstrates use of properties:
using System;
namespace tutorialspoint
{
class Student
{
private string code = "N.A";
private string name = "not known";
private int age = 0;
// Declare a Code property of type string:
public string Code
{
get
{
return code;
}
set
{
code = value;
}
}
// Declare a Name property of type string:
public string Name
{
get
{
return name;
}
set

{
name = value;
}
}
// Declare a Age property of type int:
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public override string ToString()
{
return "Code = " + Code +", Name = " + Name + ", Age = " + Age;
}
}
class ExampleDemo
{
public static void Main()
{
// Create a new Student object:
Student s = new Student();

// Setting code, name and the age of the student
s.Code = "001";
s.Name = "Zara";
s.Age = 9;
Console.WriteLine("Student Info: {0}", s);
//let us increase age
s.Age += 1;
Console.WriteLine("Student Info: {0}", s);
Console.ReadKey();
}
}

}
=================================================
When the above code is compiled and executed, it produces the following result:
Student Info: Code = 001, Name = Zara, Age = 9

Student Info: Code = 001, Name = Zara, Age = 10

Abstract Properties :
An abstract class may have an abstract property, which should be implemented in the derived class.
The following program illustrates this:

using System;
namespace tutorialspoint
{
public abstract class Person
{
public abstract string Name
{
get;
set;
}
public abstract int Age
{
get;
set;
}
}
class Student : Person
{
private string code = "N.A";
private string name = "N.A";
private int age = 0;
// Declare a Code property of type string:
public string Code
{
get
{
return code;
}
set
{
code = value;
}
}
// Declare a Name property of type string:
public override string Name
{

get
{
return name;
}
set
{
name = value;
}
}
// Declare a Age property of type int:
public override int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public override string ToString()
{
return "Code = " + Code +", Name = " + Name + ", Age = " + Age;
}
}
class ExampleDemo
{

public static void Main()
{
// Create a new Student object:
Student s = new Student();
// Setting code, name and the age of the student
s.Code = "001";
s.Name = "Zara";
s.Age = 9;
Console.WriteLine("Student Info:- {0}", s);
//let us increase age
s.Age += 1;
Console.WriteLine("Student Info:- {0}", s);
Console.ReadKey();
}
}

}
==================================================
When the above code is compiled and executed, it produces the following result:
Student Info: Code = 001, Name = Zara, Age = 9

Student Info: Code = 001, Name = Zara, Age = 10

6. INDEXERS
An indexer allows an object to be indexed such as an array. When you define an indexer for a class, this class behaves similar to a virtual array. You can then access the instance of this class using the array access operator ([ ]).
Syntax
A one dimensional indexer has the following syntax:
element-type this[int index]
{
// The get accessor.
get
{
// return the value specified by index
}
// The set accessor.
set
{
// set the value specified by index
}

}
Use of Indexers
Declaration of behavior of an indexer is to some extent similar to a property. Similar to the properties, you use get and set accessors for defining an indexer. However, properties return or set a specific data member, whereas indexers returns or sets a particular value from the object instance. In other words, it breaks the instance data into smaller parts and indexes each part, gets or sets each part.

Defining a property involves providing a property name. Indexers are not defined with names, but with the this keyword, which refers to the object instance.
The following program illustrates this:

using System;
namespace IndexerApplication
{
class IndexedNames
{
private string[] namelist = new string[size];
static public int size = 10;
public IndexedNames()
{
for (int i = 0; i < size; i++)
namelist[i] = "N. A.";
}
public string this[int index]
{
get
{
string tmp;
if( index >= 0 && index <= size-1 )
{
tmp = namelist[index];
}
else
{
tmp = "";
}
return ( tmp );
}
set
{
if( index >= 0 && index <= size-1 )
{
namelist[index] = value;
}
}
}
static void Main(string[] args)
{
IndexedNames names = new IndexedNames();
names[0] = "Zara";
names[1] = "Riz";
names[2] = "Nuha";
names[3] = "Asif";
names[4] = "Davinder";
names[5] = "Sunil";
names[6] = "Rubic";
for ( int i = 0; i < IndexedNames.size; i++ )
{
Console.WriteLine(names[i]);
}
Console.ReadKey();
}
}

}
================================================

Overloaded Indexers :

Indexers can be overloaded. Indexers can also be declared with multiple parameters and each parameter may be a different type. It is not necessary that the indexes have to be integers. C# allows indexes to be of other types, for example, a string.
The following example demonstrates overloaded indexers:

using System;
namespace IndexerApplication
{
class IndexedNames
{
private string[] namelist = new string[size];
static public int size = 10;
public IndexedNames()
{
for (int i = 0; i < size; i++)
{
namelist[i] = "N. A.";
}
}
public string this[int index]
{
get
{
string tmp;
if( index >= 0 && index <= size-1 )
{
tmp = namelist[index];
}
else
{
tmp = "";
}
return ( tmp );
}
set
{
if( index >= 0 && index <= size-1 )
{
namelist[index] = value;
}
}
}
public int this[string name]

{
get
{
int index = 0;
while(index < size)
{
if (namelist[index] == name)
{
return index;
}
index++;
}
return index;
}
}
static void Main(string[] args)
{
IndexedNames names = new IndexedNames();
names[0] = "Zara";
names[1] = "Riz";
names[2] = "Nuha";
names[3] = "Asif";
names[4] = "Davinder";
names[5] = "Sunil";
names[6] = "Rubic";
//using the first indexer with int parameter
for (int i = 0; i < IndexedNames.size; i++)

{
Console.WriteLine(names[i]);
}
//using the second indexer with the string parameter
Console.WriteLine(names["Nuha"]);
Console.ReadKey();
}
}

}
================================================

7. DELEGATES
C# delegates are similar to pointers to functions, in C or C++. A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime.

Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class.
Declaring Delegates :
Delegate declaration determines the methods that can be referenced by the delegate. A delegate can refer to a method, which has the same signature as that of the delegate.
For example, consider a delegate:
public delegate int MyDelegate (string s);

The preceding delegate can be used to reference any method that has a single stringparameter and returns an int type variable.
Syntax for delegate declaration is:

delegate <return type> <delegate-name> <parameter list>

Instantiating Delegates :

Once a delegate type is declared, a delegate object must be created with the new keyword and be associated with a particular method. When creating a delegate, the argument passed to the new expression is written similar to a method call, but without the arguments to the method.
Example : 
using System;
delegate int NumberChanger(int n);
namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num += p;
return num;
}
public static int MultNum(int q)
{
num *= q;
return num;
}
public static int getNum()
{
return num;
}
static void Main(string[] args)
{
//create delegate instances
NumberChanger nc1 = new NumberChanger(AddNum);

NumberChanger nc2 = new NumberChanger(MultNum);
//calling the methods using the delegate objects
nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}
================================================
When the above code is compiled and executed, it produces the following result:
Value of Num: 35

Value of Num: 175

Multicasting of a Delegate :
Delegate objects can be composed using the "+" operator. A composed delegate calls the two delegates it was composed from. Only delegates of the same type can be composed. The "-" operator can be used to remove a component delegate from a composed delegate.
Using this property of delegates you can create an invocation list of methods that will be called when a delegate is invoked. This is called multicasting of a delegate.

Using Delegates :
The following example demonstrates the use of delegate. The delegate printString can be used to reference method that takes a string as input and returns nothing.
We use this delegate to call two methods, the first prints the string to the console, and the second one prints it to a file:

using System;
using System.IO;
namespace DelegateAppl
{
class PrintString
{
static FileStream fs;
static StreamWriter sw;
// delegate declaration
public delegate void printString(string s);
// this method prints to the console
public static void WriteToScreen(string str)
{
Console.WriteLine("The String is: {0}", str);
}
//this method prints to a file
public static void WriteToFile(string s)
{
fs = new FileStream("c:\\message.txt",
FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs);
sw.WriteLine(s);
sw.Flush();
sw.Close();
fs.Close();
}
// this method takes the delegate as parameter and uses it to
// call the methods as required
public static void sendString(printString ps)
{
ps("Hello World");
}
static void Main(string[] args)
{
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);
sendString(ps1);
sendString(ps2);
Console.ReadKey();
}
}
}
=================================================
When the above code is compiled and executed, it produces the following result:
The String is: Hello World

8. EVENTS
Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as system generated notifications. Applications need to respond to events when they occur. For example, interrupts. Events are used for inter-process communication.
Using Delegates with Events :
The events are declared and raised in a class and associated with the event handlers using delegates within the same class or some other class. The class containing the event is used to publish the event. This is called the publisher class. Some other class that accepts this event is called the subscriber class. Events use the publisher-subscriber model.

A publisher is an object that contains the definition of the event and the delegate. The event-delegate association is also defined in this object. A publisher class object invokes the event and it is notified to other objects.
A subscriber is an object that accepts the event and provides an event handler. The delegate in the publisher class invokes the method (event handler) of the subscriber class.
Declaring Events :
To declare an event inside a class, first a delegate type for the event must be declared. For example,
public delegate void BoilerLogHandler(string status);
Next, the event itself is declared, using the event keyword:
//Defining event based on the above delegate
public event BoilerLogHandler BoilerEventLog;

Example: 
using System;

using System.IO;
namespace BoilerEventAppl
{
// boiler class
class Boiler
{
private int temp;
private int pressure;
public Boiler(int t, int p)
{
temp = t;
pressure = p;
}
public int getTemp()
{
return temp;
}
public int getPressure()
{
return pressure;
}
}
// event publisher
class DelegateBoilerEvent
{

public delegate void BoilerLogHandler(string status);
//Defining event based on the above delegate
public event BoilerLogHandler BoilerEventLog;
public void LogProcess()
{
string remarks = "O. K";
Boiler b = new Boiler(100, 12);
int t = b.getTemp();
int p = b.getPressure();
if(t > 150 || t < 80 || p < 12 || p > 15)
{
remarks = "Need Maintenance";
}
OnBoilerEventLog("Logging Info:\n");
OnBoilerEventLog("Temparature " + t + "\nPressure: " + p);
OnBoilerEventLog("\nMessage: " + remarks);
}
protected void OnBoilerEventLog(string message)
{
if (BoilerEventLog != null)
{
BoilerEventLog(message);
}
}
}
// this class keeps a provision for writing into the log file
class BoilerInfoLogger

{
FileStream fs;
StreamWriter sw;
public BoilerInfoLogger(string filename)
{
fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs);
}
public void Logger(string info)
{
sw.WriteLine(info);
}
public void Close()
{
sw.Close();
fs.Close();
}
}
// The event subscriber
public class RecordBoilerInfo
{
static void Logger(string info)
{
Console.WriteLine(info);
}//end of Logger
static void Main(string[] args)
{
BoilerInfoLogger filelog = new BoilerInfoLogger("e:\\boiler.txt");

DelegateBoilerEvent boilerEvent = new DelegateBoilerEvent();
boilerEvent.BoilerEventLog += new
DelegateBoilerEvent.BoilerLogHandler(Logger);
boilerEvent.BoilerEventLog += new
DelegateBoilerEvent.BoilerLogHandler(filelog.Logger);
boilerEvent.LogProcess();
Console.ReadLine();
filelog.Close();
}//end of main
}//end of RecordBoilerInfo

}
==================================================
When the above code is compiled and executed, it produces the following result:
Logging info:
Temperature 100
Pressure 12

Message: O. K

9. COLLECTIONS
Collection classes are specialized classes for data storage and retrieval. These classes provide support for stacks, queues, lists, and hash tables. Most collection classes implement the same interfaces.

Collection classes serve various purposes, such as allocating memory dynamically to elements and accessing a list of items on the basis of an index etc. These classes create collections of objects of the Object class, which is the base class for all data types in C#.
Collection Classes and Their Usage :
The following are the various commonly used classes of the System.Collection namespace. Click the following links to check their detail.
1 ArrayList : It represents ordered collection of an object that can be indexed individually. It is basically an alternative to an array. However, unlike array you can add and remove items from a list at a specified position using an index and the array resizes itself automatically. It also allows dynamic memory allocation, adding, searching and sorting items in the list.
2 Hashtable : It uses a key to access the elements in the collection.
A hash table is used when you need to access elements by using key, and you can identify a useful key value. Each item in the hash table has a key/value pair. The key is used to access the items in the collection.
3 SortedList : It uses a key as well as an index to access the items in a list.
A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key , it is a Hashtable. The collection of items is always sorted by the key value.
4 Stack : It represents a last-in, first out collection of object.
It is used when you need a last-in, first-out access of items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item.
5 Queue : It represents a first-in, first out collection of object.
It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue and when you remove an item, it is called deque.
6 BitArray : It represents an array of the binary representation using the values 1 and    0. It is used when you need to store the bits but do not know the number of bits in advance. You can access items from the BitArray collection by using an integer index, which starts from zero.

ArrayList Class : 
It represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. However, unlike array you can add and remove items from a list at a specified position using an index and the array resizes itself automatically. It also allows dynamic memory allocation, adding, searching and sorting items in the list.
Methods and Properties of ArrayList Class :
1 Capacity : Gets or sets the number of elements that the ArrayList can contain.
2 Count : Gets the number of elements actually contained in the ArrayList.
3 IsFixedSize : Gets a value indicating whether the ArrayList has a fixed size.
4 IsReadOnly : Gets a value indicating whether the ArrayList is read-only.
5 Item :  Gets or sets the element at the specified index.

The following table lists some of the commonly used methods of the ArrayList class:
public virtual int Add( object value );
Adds an object to the end of the ArrayList.
public virtual void AddRange( ICollection c );
Adds the elements of an ICollection to the end of the ArrayList.
public virtual void Clear();
Removes all elements from the ArrayList.
public virtual bool Contains( object item );
Determines whether an element is in the ArrayList.
public virtual ArrayList GetRange( int index, int count );
Returns an ArrayList which represents a subset of the elements in the source ArrayList.
public virtual int IndexOf(object);
Returns the zero-based index of the first occurrence of a value in the ArrayList or in a portion of it.
public virtual void Insert( int index, object value );
Inserts an element into the ArrayList at the specified index.
8 public virtual void InsertRange( int index, ICollection c );
Inserts the elements of a collection into the ArrayList at the specified index.
public virtual void Remove( object obj );

Removes the first occurrence of a specific object from the ArrayList.
10 public virtual void RemoveAt( int index );
Removes the element at the specified index of the ArrayList.
11 public virtual void RemoveRange( int index, int count );
Removes a range of elements from the ArrayList.
12 public virtual void Reverse();
Reverses the order of the elements in the ArrayList.
13 public virtual void SetRange( int index, ICollection c );
Copies the elements of a collection over a range of elements in the ArrayList.
14 public virtual void Sort();
Sorts the elements in the ArrayList.
15 public virtual void TrimToSize();
Sets the capacity to the actual number of elements in the ArrayList.

Example :  The following example demonstrates the concept:
using System;
using System.Collections;
namespace CollectionApplication
{
class Program
{
static void Main(string[] args)
{

ArrayList al = new ArrayList();
Console.WriteLine("Adding some numbers:");
al.Add(45);
al.Add(78);
al.Add(33);
al.Add(56);
al.Add(12);
al.Add(23);
al.Add(9);
Console.WriteLine("Capacity: {0} ", al.Capacity);
Console.WriteLine("Count: {0}", al.Count);
Console.Write("Content: ");
foreach (int i in al)
{
Console.Write(i + " ");
}
Console.WriteLine();
Console.Write("Sorted Content: ");
al.Sort();
foreach (int i in al)
{
Console.Write(i + " ");
}
Console.WriteLine();
Console.ReadKey();
}

}
}
=================================================

Hashtable Class :
The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. It uses the key to access the elements in the collection.

A hash table is used when you need to access elements by using key, and you can identify a useful key value. Each item in the hash table has a key/value pair. The key is used to access the items in the collection.
Methods and Properties of the Hashtable Class :
The following table lists some of the commonly used properties of the Hashtable class:
1 Count : Gets the number of key-and-value pairs contained in the Hashtable.
2 IsFixedSize : Gets a value indicating whether the Hashtable has a fixed size.
3 IsReadOnly : Gets a value indicating whether the Hashtable is read-only.
4 Item : Gets or sets the value associated with the specified key.
5 Keys : Gets an ICollection containing the keys in the Hashtable.
6 Values : Gets an ICollection containing the values in the Hashtable.

The following table lists some of the commonly used                 methods of the Hashtable class:
public virtual void Add( object key, object value );
Adds an element with the specified key and value into the Hashtable.
public virtual void Clear();
Removes all elements from the Hashtable.
public virtual bool ContainsKey( object key );
Determines whether the Hashtable contains a specific key.
public virtual bool ContainsValue( object value );
Determines whether the Hashtable contains a specific value.
public virtual void Remove( object key );

Removes the element with the specified key from the Hashtable.

Example : The following example demonstrates the concept:
using System;
using System.Collections;
namespace CollectionsApplication
{
class Program
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht.Add("001", "Zara Ali");
ht.Add("002", "Abida Rehman");
ht.Add("003", "Joe Holzner");
ht.Add("004", "Mausam Benazir Nur");
ht.Add("005", "M. Amlan");
ht.Add("006", "M. Arif");
ht.Add("007", "Ritesh Saikia");
if (ht.ContainsValue("Nuha Ali"))
{
Console.WriteLine("This student name is already in the
list");
}
else
{
ht.Add("008", "Nuha Ali");
}
// Get a collection of the keys.
ICollection key = ht.Keys;
foreach (string k in key)
{
Console.WriteLine(k + ": " + ht[k]);
}
Console.ReadKey();
}
}

}
=================================================
When the above code is compiled and executed, it produces the following result:
001: Zara Ali
002: Abida Rehman
003: Joe Holzner
004: Mausam Benazir Nur

005: M. Amlan
006: M. Arif
007: Ritesh Saikia
008: Nuha Ali

SortedList Class :
The SortedList class represents a collection of key-and-value pairs that are sorted by the keys and are accessible by key and by index.
A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key, it is a Hashtable. The collection of items is always sorted by the key value.
Methods and Properties of the SortedList Class :
The following table lists some of the commonly used properties of the SortedList class:
1 Capacity : Gets or sets the capacity of the SortedList.
2 Count : Gets the number of elements contained in the SortedList.
 3 IsFixedSize : Gets a value indicating whether the SortedList has a fixed size.
4 IsReadOnly : Gets a value indicating whether the SortedList is read-only.
5 Item : Gets and sets the value associated with a specific key in the SortedList.
6 Keys : Gets the keys in the SortedList.
7 Values : Gets the values in the SortedList.

The following table lists some of the commonly used methods of the SortedList class:
public virtual void Add( object key, object value );
Adds an element with the specified key and value into the SortedList.
public virtual void Clear();
Removes all elements from the SortedList.
public virtual bool ContainsKey( object key );
Determines whether the SortedList contains a specific key.
public virtual bool ContainsValue( object value );
Determines whether the SortedList contains a specific value.
public virtual object GetByIndex( int index );
Gets the value at the specified index of the SortedList.
public virtual object GetKey( int index );
Gets the key at the specified index of the SortedList.
public virtual IList GetKeyList();
Gets the keys in the SortedList.
public virtual IList GetValueList();
Gets the values in the SortedList.
public virtual int IndexOfKey( object key );
Returns the zero-based index of the specified key in the SortedList.
10 public virtual int IndexOfValue( object value );
Returns the zero-based index of the first occurrence of the specified value in the SortedList.
11 public virtual void Remove( object key );
Removes the element with the specified key from the SortedList.
12 public virtual void RemoveAt( int index );
Removes the element at the specified index of SortedList.
13 public virtual void TrimToSize();

Sets the capacity to the actual number of elements in the SortedList.

Example : The following example demonstrates the concept:
using System;
using System.Collections;
namespace CollectionsApplication
{
class Program
{
static void Main(string[] args)
{
SortedList sl = new SortedList();
sl.Add("001", "Zara Ali");
sl.Add("002", "Abida Rehman");
sl.Add("003", "Joe Holzner");
sl.Add("004", "Mausam Benazir Nur");
sl.Add("005", "M. Amlan");
sl.Add("006", "M. Arif");
sl.Add("007", "Ritesh Saikia");
if (sl.ContainsValue("Nuha Ali"))
{
Console.WriteLine("This student name is already in the
list");
}
else
{
sl.Add("008", "Nuha Ali");
}
// get a collection of the keys.
ICollection key = sl.Keys;
foreach (string k in key)
{
Console.WriteLine(k + ": " + sl[k]);
}
}
}

}
=================================================

Stack Class :

It represents a last-in, first out collection of object. It is used when you need a last-in, first-out access of items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item.
Methods and Properties of the Stack Class :
1 Count :  Gets the number of elements contained in the Stack.

Some of the commonly used methods of the Stack class:
public virtual void Clear();
Removes all elements from the Stack.
public virtual bool Contains( object obj );
Determines whether an element is in the Stack.
public virtual object Peek();
Returns the object at the top of the Stack without removing it.
public virtual object Pop();
Removes and returns the object at the top of the Stack.
public virtual void Push( object obj );
Inserts an object at the top of the Stack.
public virtual object[] ToArray();
Copies the Stack to a new array.

Example :  The following example demonstrates use of Stack:

using System;
using System.Collections;
namespace CollectionsApplication
{
class Program
{
static void Main(string[] args)
{
Stack st = new Stack();
st.Push('A');
st.Push('M');
st.Push('G');
st.Push('W');
Console.WriteLine("Current stack: ");
foreach (char c in st)
{
Console.Write(c + " ");
}
Console.WriteLine();
st.Push('V');
st.Push('H');
Console.WriteLine("The next poppable value in stack: {0}",
st.Peek());
Console.WriteLine("Current stack: ");
foreach (char c in st)
{
Console.Write(c + " ");
}
Console.WriteLine();
Console.WriteLine("Removing values ");
st.Pop();
st.Pop();
st.Pop();
Console.WriteLine("Current stack: ");
foreach (char c in st)
{
Console.Write(c + " ");
}
}
}

}
=================================================

Queue Class :

It represents a first-in, first out collection of object. It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue, and when you remove an item, it is called deque.
Methods and Properties of the Queue Class :
1 Count : Gets the number of elements contained in the Queue.

The following table lists some of the commonly used methods of the Queue class:
public virtual void Clear();
Removes all elements from the Queue.
public virtual bool Contains( object obj );
Determines whether an element is in the Queue.
public virtual object Dequeue();
Removes and returns the object at the beginning of the Queue.
public virtual void Enqueue( object obj );
Adds an object to the end of the Queue.
public virtual object[] ToArray();
Copies the Queue to a new array.
public virtual void TrimToSize();
Sets the capacity to the actual number of elements in the Queue.

Example : The following example demonstrates use of Stack:

using System;
using System.Collections;
namespace CollectionsApplication
{
class Program
{
static void Main(string[] args)
{
Queue q = new Queue();
q.Enqueue('A');
q.Enqueue('M');
q.Enqueue('G');
q.Enqueue('W');
Console.WriteLine("Current queue: ");
foreach (char c in q)
Console.Write(c + " ");
Console.WriteLine();
q.Enqueue('V');
q.Enqueue('H');
Console.WriteLine("Current queue: ");
foreach (char c in q)
Console.Write(c + " ");
Console.WriteLine();
Console.WriteLine("Removing some values ");
char ch = (char)q.Dequeue();
Console.WriteLine("The removed value: {0}", ch);
ch = (char)q.Dequeue();
Console.WriteLine("The removed value: {0}", ch);
Console.ReadKey();
}
}

}
================================================
BitArray Class :
The BitArray class manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on (1) and false indicates the bit is off (0).

It is used when you need to store the bits but do not know the number of bits in advance. You can access items from the BitArray collection by using an integer index, which starts from zero.
Methods and Properties of the BitArray Class :
The following table lists some of the commonly used properties of the BitArray class:
1 Count : Gets the number of elements contained in the BitArray.
2 IsReadOnly : Gets a value indicating whether the BitArray is read-only.
3 Item : Gets or sets the value of the bit at a specific position in the BitArray.
4 Length : Gets or sets the number of elements in the BitArray.

The following table lists some of the commonly used methods of the BitArray class:
public BitArray And( BitArray value );
Performs the bitwise AND operation on the elements in the current BitArray against the corresponding elements in the specified BitArray.
public bool Get( int index );
Gets the value of the bit at a specific position in the BitArray.
public BitArray Not();
Inverts all the bit values in the current BitArray, so that elements set to true are changed to false, and elements set to false are changed to true.
public BitArray Or( BitArray value );
Performs the bitwise OR operation on the elements in the current BitArray against the corresponding elements in the specified BitArray.
public void Set( int index, bool value );
Sets the bit at a specific position in the BitArray to the specified value.
public void SetAll( bool value );
Sets all bits in the BitArray to the specified value.
public BitArray Xor( BitArray value );
Performs the bitwise eXclusive OR operation on the elements in the current BitArray against the corresponding elements in the specified BitArray.

Example : The following example demonstrates the use of BitArray class:

using System;
using System.Collections;
namespace CollectionsApplication
{
class Program
{
static void Main(string[] args)
{
//creating two bit arrays of size 8
BitArray ba1 = new BitArray(8);
BitArray ba2 = new BitArray(8);
byte[] a = { 60 };
byte[] b = { 13 };
//storing the values 60, and 13 into the bit arrays
ba1 = new BitArray(a);
ba2 = new BitArray(b);
//content of ba1
Console.WriteLine("Bit array ba1: 60");
for (int i = 0; i < ba1.Count; i++)
{
Console.Write("{0, -6} ", ba1[i]);
}
Console.WriteLine();
//content of ba2
Console.WriteLine("Bit array ba2: 13");
for (int i = 0; i < ba2.Count; i++)
{
Console.Write("{0, -6} ", ba2[i]);
}
Console.WriteLine();
BitArray ba3 = new BitArray(8);
ba3 = ba1.And(ba2);
//content of ba3
Console.WriteLine("Bit array ba3 after AND operation: 12");
for (int i = 0; i < ba3.Count; i++)
{
Console.Write("{0, -6} ", ba3[i]);
}
Console.WriteLine();
ba3 = ba1.Or(ba2);
//content of ba3
Console.WriteLine("Bit array ba3 after OR operation: 61");
for (int i = 0; i < ba3.Count; i++)
{

Console.Write("{0, -6} ", ba3[i]);
}
Console.WriteLine();
Console.ReadKey();
}
}

}
==============================================

10. GENERICS
Generics allow you to delay the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.

You write the specifications for the class or the method, with substitute parameters for data types. When the compiler encounters a constructor for the class or a function call for the method, it generates code to handle the specific data type.

Example :
using System;
using System.Collections.Generic;
namespace GenericApplication
{
public class MyGenericArray<T>
{
private T[] array;
public MyGenericArray(int size)
{
array = new T[size + 1];
}
public T getItem(int index)
{
return array[index];
}
public void setItem(int index, T value)
{
array[index] = value;

}
}
class Tester
{
static void Main(string[] args)
{
//declaring an int array
MyGenericArray<int> intArray = new MyGenericArray<int>(5);
//setting values
for (int c = 0; c < 5; c++)
{
intArray.setItem(c, c*5);
}
//retrieving the values
for (int c = 0; c < 5; c++)
{
Console.Write(intArray.getItem(c) + " ");
}
Console.WriteLine();
//declaring a character array
MyGenericArray<char> charArray = new MyGenericArray<char>(5);
//setting values
for (int c = 0; c < 5; c++)
{
charArray.setItem(c, (char)(c+97));
}
//retrieving the values
for (int c = 0; c< 5; c++)

{
Console.Write(charArray.getItem(c) + " ");
}
Console.WriteLine();
Console.ReadKey();
}
}

}
==============================================
When the above code is compiled and executed, it produces the following result:
0 5 10 15 20

a b c d e

Features of Generics :
Generics is a technique that enriches your programs in the following ways:
 It helps you to maximize code reuse, type safety, and performance.
 You can create generic collection classes. The .NET Framework class library contains several new generic collection classes in the System.Collections.Genericnamespace. You may use these generic collection classes instead of the collection classes in the System.Collections namespace.
 You can create your own generic interfaces, classes, methods, events, and delegates.
 You may create generic classes constrained to enable access to methods on particular data types.
 You may get information on the types used in a generic data type at run-time by means of reflection.

Generic Methods :
We have used a generic class; we can declare a generic method with a type parameter. The following program illustrates the concept:

using System;
using System.Collections.Generic;
namespace GenericMethodAppl
{
class Program
{
static void Swap<T>(ref T lhs, ref T rhs)
{
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}
static void Main(string[] args)
{
int a, b;
char c, d;
a = 10;
b = 20;
c = 'I';
d = 'V';
//display values before swap:
Console.WriteLine("Int values before calling swap:");
Console.WriteLine("a = {0}, b = {1}", a, b);
Console.WriteLine("Char values before calling swap:");
Console.WriteLine("c = {0}, d = {1}", c, d);
//call swap
Swap<int>(ref a, ref b);
Swap<char>(ref c, ref d);

//display values after swap:
Console.WriteLine("Int values after calling swap:");
Console.WriteLine("a = {0}, b = {1}", a, b);
Console.WriteLine("Char values after calling swap:");
Console.WriteLine("c = {0}, d = {1}", c, d);
Console.ReadKey();
}
}

}
==================================================

Generic Delegates :
You can define a generic delegate with type parameters. For example:
delegate T NumberChanger<T>(T n);


The following example shows use of this delegate:

using System;
using System.Collections.Generic;
delegate T NumberChanger<T>(T n);
namespace GenericDelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num += p;
return num;
}
public static int MultNum(int q)
{
num *= q;
return num;
}
public static int getNum()
{
return num;
}
static void Main(string[] args)
{
//create delegate instances
NumberChanger<int> nc1 = new NumberChanger<int>(AddNum);
NumberChanger<int> nc2 = new NumberChanger<int>(MultNum);
//calling the methods using the delegate objects
nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);

Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}

}
=================================================

11. ANONYMOUS METHODS
We discussed that delegates are used to reference any methods that has the same signature as that of the delegate. In other words, you can call a method that can be referenced by a delegate using that delegate object.
Anonymous methods provide a technique to pass a code block as a delegate parameter. Anonymous methods are the methods without a name, just the body.

You need not specify the return type in an anonymous method; it is inferred from the return statement inside the method body.
Writing an Anonymous Method :
Anonymous methods are declared with the creation of the delegate instance, with adelegate keyword. For example,
delegate void NumberChanger(int n);
...
NumberChanger nc = delegate(int x)
{
Console.WriteLine("Anonymous Method: {0}", x);
};
The code block Console.WriteLine("Anonymous Method: {0}", x); is the body of the anonymous method.
Example : The following example demonstrates the concept:

using System;
delegate void NumberChanger(int n);
namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;
public static void AddNum(int p)
{
num += p;
Console.WriteLine("Named Method: {0}", num);
}
public static void MultNum(int q)
{
num *= q;
Console.WriteLine("Named Method: {0}", num);
}
public static int getNum()
{
return num;
}
static void Main(string[] args)
{
//create delegate instances using anonymous method
NumberChanger nc = delegate(int x)
{
Console.WriteLine("Anonymous Method: {0}", x);

};
//calling the delegate using the anonymous method
nc(10);
//instantiating the delegate using the named methods
nc = new NumberChanger(AddNum);
//calling the delegate using the named methods
nc(5);
//instantiating the delegate using another named methods
nc = new NumberChanger(MultNum);
//calling the delegate using the named methods
nc(2);
Console.ReadKey();
}
}

}
=================================================
When the above code is compiled and executed, it produces the following result:
Anonymous Method: 10
Named Method: 15

Named Method: 30

12. UNSAFE CODES
C# allows using pointer variables in a function of code block when it is marked by the unsafe modifier. The unsafe code or the unmanaged code is a code block that uses a pointer variable.
Pointers
A pointer is a variable whose value is the address of another variable i.e., the direct address of the memory location. Similar to any variable or constant, you must declare a pointer before you can use it to store any variable address.
The general form of a pointer declaration is:
type *var-name;

Following are valid pointer declarations:
int *ip; /* pointer to an integer */ 
double *dp; /* pointer to a double */ 
float *fp; /* pointer to a float */ 
char *ch /* pointer to a character */ 
The following example illustrates use of pointers in C#, using the unsafe modifier:

using System; 
namespace UnsafeCodeApplication 

class Program 

static unsafe void Main(string[] args) 

int var = 20; 
int* p = &var; 
Console.WriteLine("Data is: {0} ", var); 
Console.WriteLine("Address is: {0}", (int)p); 
Console.ReadKey(); 



============================================================
When the above code was compiled and executed, it produces the following result:
Data is: 20
Address is: 99215364
Retrieving the Data Value Using a Pointer  :
You can retrieve the data stored at the located referenced by the pointer variable, using theToString() method.

using System; 
namespace UnsafeCodeApplication 

class Program 

public static void Main() 

unsafe 

int var = 20; 
int* p = &var; 
Console.WriteLine("Data is: {0} " , var); 
Console.WriteLine("Data is: {0} " , p->ToString()); 
Console.WriteLine("Address is: {0} " , (int)p); 

Console.ReadKey(); 



============================================================
When the above code was compiled and executed, it produces the following result:
Data is: 20
Data is: 20
Address is: 77128984
Passing Pointers as Parameters to Methods :
You can pass a pointer variable to a method as parameter. The following example illustrates this: 
using System; 
namespace UnsafeCodeApplication 

class TestPointer 

public unsafe void swap(int* p, int *q) 

int temp = *p; 
*p = *q; 
*q = temp; 

public unsafe static void Main() 

TestPointer p = new TestPointer(); 
int var1 = 10; 
int var2 = 20; 
int* x = &var1; 
int* y = &var2; 
Console.WriteLine("Before Swap: var1:{0}, var2: {1}", var1, var2); 
p.swap(x, y); 
Console.WriteLine("After Swap: var1:{0}, var2: {1}", var1, var2); 
Console.ReadKey(); 



============================================================
When the above code is compiled and executed, it produces the following result:
Before Swap: var1: 10, var2: 20
After Swap: var1: 20, var2: 10

Accessing Array Elements Using a Pointer :
In C#, an array name and a pointer to a data type same as the array data, are not the same variable type. For example, int *p and int[] p, are not same type. You can increment the pointer variable p because it is not fixed in memory but an array address is fixed in memory, and you can't increment that.
Therefore, if you need to access an array data using a pointer variable, as we traditionally do in C, or C++ ( please check: C Pointers), you need to fix the pointer using the fixed keyword.
The following example demonstrates this:

using System;
namespace UnsafeCodeApplication
{
class TestPointer
{
public unsafe static void Main()
{
int[] list = {10, 100, 200};
fixed(int *ptr = list)
/* let us have array address in pointer */
for ( int i = 0; i < 3; i++)
{
Console.WriteLine("Address of list[{0}]={1}",i,(int)(ptr + i));
Console.WriteLine("Value of list[{0}]={1}", i, *(ptr + i));
}
Console.ReadKey();
}
}

}
================================================

Compiling Unsafe Code :
For compiling unsafe code, you have to specify the /unsafe command-line switch with command-line compiler.
For example, to compile a program named prog1.cs containing unsafe code, from command line, give the command:

csc /unsafe prog1.cs

If you are using Visual Studio IDE then you need to enable use of unsafe code in the project properties.
To do this:
 Open project properties by double clicking the properties node in the Solution Explorer.
 Click on the Build tab.

 Select the option "Allow unsafe code".

13. MULTITHREADING
A thread is defined as the execution path of a program. Each thread defines a unique flow of control. If your application involves complicated and time consuming operations, then it is often helpful to set different execution paths or threads, with each thread performing a particular job.
Threads are lightweight processes. One common example of use of thread is implementation of concurrent programming by modern operating systems. Use of threads saves wastage of CPU cycle and increase efficiency of an application.

So far we wrote the programs where a single thread runs as a single process which is the running instance of the application. However, this way the application can perform one job at a time. To make it execute more than one task at a time, it could be divided into smaller threads.
Thread Life Cycle :
The life cycle of a thread starts when an object of the System.Threading.Thread class is created and ends when the thread is terminated or completes execution.
Following are the various states in the life cycle of a thread:
 The Unstarted State: It is the situation when the instance of the thread is created but the Start method is not called.
The Ready State: It is the situation when the thread is ready to run and waiting CPU cycle.
 The Not Runnable State: A thread is not executable, when:
* Sleep method has been called
* Wait method has been called
* Blocked by I/O operations
 The Dead State: It is the situation when the thread completes execution or is aborted.

The Main Thread :
In C#, the System.Threading.Thread class is used for working with threads. It allows creating and accessing individual threads in a multithreaded application. The first thread to be executed in a process is called the main thread.
When a C# program starts execution, the main thread is automatically created. The threads created using the Thread class are called the child threads of the main thread. You can access a thread using the CurrentThread property of the Thread class.
The following program demonstrates main thread execution:

using System;
using System.Threading;
namespace MultithreadingApplication
{
class MainThreadProgram
{
static void Main(string[] args)
{
Thread th = Thread.CurrentThread;
th.Name = "MainThread";
Console.WriteLine("This is {0}", th.Name);
Console.ReadKey();
}
}
}
================================================
When the above code is compiled and executed, it produces the following result:
This is MainThread

The following program demonstrates main thread execution:
using System;
using System.Threading;
namespace MultithreadingApplication
{
class MainThreadProgram
{
static void Main(string[] args)
{
Thread th = Thread.CurrentThread;
th.Name = "MainThread";
Console.WriteLine("This is {0}", th.Name);
Console.ReadKey();
}
}
}
================================================
When the above code is compiled and executed, it produces the following result:
This is MainThread

Properties and Methods of the Thread Class :

Some most commonly used properties of the Thread class:
1 CurrentContext : Gets the current context in which the thread is executing.
2 CurrentCulture : Gets or sets the culture for the current thread.
3 CurrentPrinciple : Gets or sets the thread's current principal (for role-based security).
4 CurrentThread : Gets the currently running thread.
5 CurrentUICulture : Gets or sets the current culture used by the Resource Manager to look up culture-specific resources at run-time.
6 ExecutionContext : Gets an ExecutionContext object that contains information about the various contexts of the current thread.
7 IsAlive : Gets a value indicating the execution status of the current thread.
8 IsBackground : Gets or sets a value indicating whether or not a thread is a background thread.
9 IsThreadPoolThread : Gets a value indicating whether or not a thread belongs to the managed thread pool.
10 ManagedThreadId : Gets a unique identifier for the current managed thread.
11 Name : Gets or sets the name of the thread.
12 Priority : Gets or sets a value indicating the scheduling priority of a thread.
13 ThreadState : Gets a value containing the states of the current thread.

Some of the most commonly used methods of the Thread class:
public void Abort() : 

Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread.
public static LocalDataStoreSlot AllocateDataSlot()
Allocates an unnamed data slot on all the threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
public static LocalDataStoreSlot AllocateNamedDataSlot( string name)
Allocates a named data slot on all threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
public static void BeginCriticalRegion()
Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception might jeopardize other tasks in the application domain.
public static void BeginThreadAffinity()
Notifies a host that managed code is about to execute instructions that depend on the identity of the current physical operating system thread.
public static void EndCriticalRegion()
Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception are limited to the current task.
public static void EndThreadAffinity()
Notifies a host that managed code has finished executing instructions that depend on the identity of the current physical operating system thread.
public static void FreeNamedDataSlot(string name)
Eliminates the association between a name and a slot, for all threads in the process. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
public static Object GetData( LocalDataStoreSlot slot )
Retrieves the value from the specified slot on the current thread, within the current thread's current domain. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
10 public static AppDomain GetDomain()
Returns the current domain in which the current thread is running.
11 public static AppDomain GetDomain()
Returns a unique application domain identifier
12 public static LocalDataStoreSlot GetNamedDataSlot( string name )
Looks up a named data slot. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
13 public void Interrupt()
Interrupts a thread that is in the WaitSleepJoin thread state.
14 public void Join()
Blocks the calling thread until a thread terminates, while continuing to perform standard COM and SendMessage pumping. This method has different overloaded forms.
15 public static void MemoryBarrier()
Synchronizes memory access as follows: The processor executing the current thread cannot reorder instructions in such a way that memory accesses prior to the call to MemoryBarrier execute after memory accesses that follow the call to MemoryBarrier.
16 public static void ResetAbort()
Cancels an Abort requested for the current thread.
17 public static void SetData( LocalDataStoreSlot slot, Object data )
Sets the data in the specified slot on the currently running thread, for that thread's current domain. For better performance, use fields marked with the ThreadStaticAttribute attribute instead.
18 public void Start()
Starts a thread.
19 public static void Sleep( int millisecondsTimeout )
Makes the thread pause for a period of time.
20 public static void SpinWait( int iterations )
Causes a thread to wait the number of times defined by the iterations parameter
21 public static byte VolatileRead( ref byte address ) 
public static double VolatileRead( ref double address ) 
public static int VolatileRead( ref int address )
 public static Object VolatileRead( ref Object address )
Reads the value of a field. The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache. This method has different overloaded forms. Only some are given above.
22 public static void VolatileWrite( ref byte address, byte value ) 
public static void VolatileWrite( ref double address, double value ) 
public static void VolatileWrite( ref int address, int value ) 
public static void VolatileWrite( ref Object address, Object value )
Writes a value to a field immediately, so that the value is visible to all processors in the computer. This method has different overloaded forms. Only some are given above.
23 public static bool Yield()
Causes the calling thread to yield execution to another thread that is ready to run on the current processor. The operating system selects the thread to yield to.
Creating Threads :
Threads are created by extending the Thread class. The extended Thread class then calls the Start() method to begin the child thread execution.
The following program demonstrates the concept:

using System;
using System.Threading;
namespace MultithreadingApplication
{
class ThreadCreationProgram
{
public static void CallToChildThread()
{
Console.WriteLine("Child thread starts");
}
static void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
Console.ReadKey();
}
}
}
=============================================
When the above code is compiled and executed, it produces the following result:
In Main: Creating the Child thread
Child thread starts

Managing Threads :
The Thread class provides various methods for managing threads.
The following example demonstrates the use of the sleep() method for making a thread pause for a specific period of time.

using System;
using System.Threading;
namespace MultithreadingApplication
{
class ThreadCreationProgram
{
public static void CallToChildThread()
{
Console.WriteLine("Child thread starts");
// the thread is paused for 5000 milliseconds
int sleepfor = 5000;
Console.WriteLine("Child Thread Paused for {0} seconds",
sleepfor / 1000);
Thread.Sleep(sleepfor);
Console.WriteLine("Child thread resumes");
}
static void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
Console.ReadKey();
}
}

}
================================================
When the above code is compiled and executed, it produces the following result:
In Main: Creating the Child thread
Child thread starts
Child Thread Paused for 5 seconds

Child thread resumes

Destroying Threads :
The Abort() method is used for destroying threads.
The runtime aborts the thread by throwing a ThreadAbortException. This exception cannot be caught, the control is sent to the finally block, if any.
The following program illustrates this:

using System;
using System.Threading;
namespace MultithreadingApplication
{
class ThreadCreationProgram
{
public static void CallToChildThread()
{
try
{
Console.WriteLine("Child thread starts");
// do some work, like counting to 10
for (int counter = 0; counter <= 10; counter++)
{
Thread.Sleep(500);
Console.WriteLine(counter);
}
Console.WriteLine("Child Thread Completed");
}
catch (ThreadAbortException e)

{
Console.WriteLine("Thread Abort Exception");
}
finally
{
Console.WriteLine("Couldn't catch the Thread Exception");
}
}
static void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
//stop the main thread for some time
Thread.Sleep(2000);
//now abort the child
Console.WriteLine("In Main: Aborting the Child thread");
childThread.Abort();
Console.ReadKey();
}
}
}
==============================================
When the above code is compiled and executed, it produces the following result:
In Main: Creating the Child thread
Child thread starts

0
1
2
In Main: Aborting the Child thread
Thread Abort Exception
Couldn't catch the Thread Exception
===========================================================

Conclusion :
Thus in this article we have seen what assemblies are in Microsoft .NET Framewok with C# . We have seen  single file and multi file assemblies. We have also seen private and public assemblies.We have also taken a look at application domains and how they are supported in .NET.


"I hope this information will be fulfill whoes like Programming." 
RAJ KUMAR
( Software Engg )



If you think to a making  a website Please contect me with low price . 
Contect Email : 10julyRAJKUMAR@gmail.com