Vous êtes sur la page 1sur 82

.

Net Basics & C#:


.Net Program Execution:
Let us now understand, how a .Net program executes. Using dotnet we can
create different types of applications. A few of the common types of .NET
applications include Web, Windows, Console and Mobile Applications. Irrespective
of the type of the application, when you execute any .NET application the
following happens
1. The .NET application gets compiled into Intermediate language (IL). IL is also
referred as Common Intermediate language (CIL) and Microsoft Intermediate
language (MSIL). Both .NET and non .NET applications generate an assembly.
Assemblies have an extension of .DLL or .EXE. For example if you compile a
windows or Console application, you get a .EXE, where as when we compile a
web or Class library project we get a .DLL. The difference between a .NET and
NON .NET assembly is that, DOTNET Assembly is in intermediate language
format where as NON DOTNET assembly is in native code format.
2. NON DOTNET applications can run directly on top of the operating system,
where as DOTNET applications run on top of a virtual environment called as
Common Language Runtime (CLR). CLR contains a component called Just In-Time
Compiler (JIT), which will convert the Intermediate language into native code
which the underlying operating system can understand.
So, in .NET the application execution consists of 2 steps
1. Language compiler, compiles the Source Code into Intermediate Language (IL)
2. JIT compiler in CLR converts, the IL into native code which can then be run on
the underlying operating system.
Since, a .NET assembly is in Intermedaite Language format and not native
code, .NET assemblies are portable to any platform, as long as the target
platform has the Common Language Runtime (CLR). The target platform's CLR
converts the Intermedaite Language into native code that the underlying
operating system can understand. Intermediate Languge is also called as
managed code. This is because CLR manages the code that runs inside it. For
example, in a VB6 program, the developer is responsible for de-allocating the
memory consumed by an object. If a programmer forgets to de-allocate memory,
we may run into hard to detecct out of memory exceptions. On the other hand
a .NET programmer need not worry about de-allocating the memory consumed
by an object. Automatic memory management, also known as grabage collection
is provided by CLR. Apart, from garbage collection, there are several other
benefits provided by the CLR, which we will discuss in a later session. Since, CLR
is managing and executing the Intermediate Language, it (IL) is also called as
managed code.

ILDASM and ILASM


To peek inside an assembly with ILDASM follow these steps.
1. Navigate to Visual Studio Command Prompt (Start -> All Programs ->
Microsoft Visual Studio 2010 -> Visual Studio Tools -> Right Click on Visual Studio

Command Prompt 2012 and select "Run as Administrator")


2. Once you have the "Visual Studio Command Prompt 2012" open, type in the
following command and press enter
Ildasm.exe C:\YourDirectoryPath\YourAssembly.exe
This command should open the assembly and you will find the manifest and the
types (classes, structs etc..) in the assembly. At the bottom you can see the
version of the assembly.
If you want to save the Intermediate Language to a text file.
1. Select File Menu from the ILDASM tool.
2. Select Dump and you will see "Dump Options Window"
3. Click OK on "Dump Options Window"
4. Now enter the file name of your choice. For this example let's enter sample
and save it to the C: drive.
5. Now navigate to C: drive in windows explorer and you should see Sample.il
6. Open Sample.il with notepad and you should see assembly metadata and
IL(Intermediate Language).
If you want to rebuild an Assembly from the Sample.il file we can use a
tool ILASM.exe
1. Type the following command in "Visual Studio Command Prompt" and press
enter
ILASM.exe C:\Sample.il
2. Now navigate to C: drive in windows explorer and you should see Sample.exe
We use ILDASM (Intermediate Language Disassembler) to peek at the
assembly manifest and IL. You can also use this tool to export manifest
and IL to a text file.
We use ILASM.exe (Intermediate Language Assembler) to reconstruct
an assembly from a text file that contains manifest and IL.
ASSEMBLY IN .NET FRAMEWORK:
The .NET assembly is the standard for components developed with the
Microsoft.NET. Dot NET assemblies may or may not be executable, i.e., they
might exist as the executable (.exe) file or dynamic link library (DLL) file. All
the .NET assemblies contain the definition of types, versioning information for
the type, meta-data, and manifest. The designers of .NET have worked a lot on
the component (assembly) resolution.
There are two kind of assemblies in .NET;
private
shared

What is GAC. How and when to install an assembly into GAC

Abbreviated as GAC, the Global Assembly Cache is a machine-wide store used to hold assemblies that are
intended to be shared by several applications on the machine. Each computer where the common language
runtime (CLR) is installed has a global assembly cache. The global assembly cache stores the assemblies
specifically designated to be shared by several applications on the computer.
The .NET Framework provides two tools for working with the cache. One is a Windows shell extension that
allows you to work with the cache using a Graphical User Interface (GUI). The other is a command line tool,
called the Global Assembly Cache tool (Gacutil.exe), that is typically used in build and test scripts.

What is DLL HELL in .NET:


1. I have 2 applications, A1 and A2 installed on my computer.
2. Both of these applications use shared assembly shared.dll
3. Now, I have a latest version of Application - A2 available on the internet.
4. I download the latest version of A2 and install it on my machine.
5. This new installation has over written Shared.dll, which is also used by Application - A1.
6. Application - A2 works fine, but A1 fails to work, because the newly installed Shared.dll is not
backward compatible.
So, DLL HELL is a problem where one application will install a new version of the shared component
that is not backward compatible with the version already on the machine, causing all the other existing
applications that rely on the shared component to break. With .NET versioning we donot have DLL
HELL problem any more.

How is the DLL HELL problem solved in .NET


Consider the example below:
I have 2 applications, Application - A1 and Application - A2 which relies on the shared
assembly Accessibility.dll (Version 2.0.0.0) as shown in the image below.

2. Now, I have a latest version of Application - A2 available on the internet.


3. I download the latest version of A2 and install it on my machine.
4. This new installation copies a newer version of Accessibility.dll into the GAC with version 3.0.0.0.
5. So, in the GAC we now have 2 versions of Accessibility.dll.

6. Application - A1 continues to use Accessibility.dll (version 2.0.0.0) and Application - A2 uses


Accessibility.dll (version 3.0.0.0)
7. So, now the assemblies are able to reside side by side in the GAC. For this reason dot net
assemblies are also said to be supporting side by side execution.

C#
In C# types are divided into 2 broad categories.
Value Types - int, float, double, structs, enums etc
Reference Types Interface, Class, delegates, arrays etc
By default value types are non nullable. To make them nullable use ?
int i = 0 (i is non nullable, so "i" cannot be set to null, i = null will generate compiler error)
int? j = 0 (j is nullable int, so j=null is legal)
NULL coalescing operator:
Program without using NULL coalescing operator
using System;
class Program
{
static void Main()
{
int AvailableTickets;
int? TicketsOnSale = null;
if (TicketsOnSale == null)
{
AvailableTickets = 0;
}
else
{
AvailableTickets = (int)TicketsOnSale;
}
Console.WriteLine("Available Tickets={0}", AvailableTickets);
}
}
The above program is re-written using NULL coalescing operator
using System;
class Program
{
static void Main()
{
int AvailableTickets;
int? TicketsOnSale = null;
//Using null coalesce operator ??
AvailableTickets = TicketsOnSale ?? 0;
Console.WriteLine("Available Tickets={0}", AvailableTickets);

}
}
Datatype conversions

Implicit conversion is done by the compiler:


1. When there is no loss of information if the conversion is done
2. If there is no possibility of throwing exceptions during the conversion

Example: Converting an int to a float will not loose any data and no exception will be
thrown, hence an implicit conversion can be done.
Where as when converting a float to an int, we loose the fractional part and also a
possibility of overflow exception. Hence, in this case an explicit conversion is required. For
explicit conversion we can use cast operator or the convert class in c#.
Implicit Conversion Example
using System;
class Program
{
public static void Main()
{
int i = 100;
// float is bigger datatype than int. So, no loss of
// data and exceptions. Hence implicit conversion
float f = i;
Console.WriteLine(f);
}
}
Explicit Conversion Example
using System;
class Program
{
public static void Main()
{
float f = 100.25F;
// Cannot implicitly convert float to int.
// Fractional part will be lost. Float is a
// bigger datatype than int, so there is
// also a possiblity of overflow exception
// int i = f;
// Use explicit conversion using cast () operator
int i = (int)f;
// OR use Convert class
// int i = Convert.ToInt32(f);

Console.WriteLine(i);
}
}
Difference between Parse and TryParse
1. If the number is in a string format you have 2 options - Parse() and TryParse()
2. Parse() method throws an exception if it cannot parse the value, whereas TryParse()
returns a bool indicating whether it succeeded or failed.
3. Use Parse() if you are sure the value will be valid, otherwise use TryParse()

ARRAYS IN C#

An array is a collection of similar data types.


using System;
class Program
{
public static void Main()
{
// Initialize and assign values in different lines
int[] EvenNumbers = new int[3];
EvenNumbers[0] = 0;
EvenNumbers[1] = 2;
EvenNumbers[2] = 4;
// Initialize and assign values in the same line
int[] OddNumbers = { 1, 3, 5};
Console.WriteLine("Printing EVEN Numbers");
// Retrieve and print even numbers from the array
for (int i = 0; i < EvenNumbers.Length; i++)
{
Console.WriteLine(EvenNumbers[i]);
}
Console.WriteLine("Printing ODD Numbers");
// Retrieve and print odd numbers from the array
for (int i = 0; i < OddNumbers.Length; i++)
{
Console.WriteLine(OddNumbers[i]);
}
}
}

Advantages: Arrays are strongly typed.

Disadvantages: Arrays cannot grow in size once initialized. Have to rely on integral indices
to store or retrieve items from the array.

METHOD HIDING (EXAMPLE 1)

METHOD OVERRIDING & HIDING (EXAMPLE 2)

METHOD OVERRIDING & HIDING (EXAMPLE 3)

Polymorphism:
When a message can be processed in different ways is called polymorphism.
Polymorphism means many forms.

Polymorphism is one of the fundamental concepts of OOP.

Polymorphism provides following features:

It allows you to invoke methods of derived class through base class reference

during runtime.
It has the ability for classes to provide different implementations of methods that
are called through the same name.

Polymorphism is of two types:

1. Compile time polymorphism/Overloading


2. Runtime polymorphism/Overriding
Compile Time Polymorphism

Compile time polymorphism is method and operators overloading. It is also called early
binding.

In method overloading method performs the different task at the different input
parameters.

Runtime Time Polymorphism

Runtime time polymorphism is done using inheritance and virtual functions. Method
overriding is called runtime polymorphism. It is also called late binding.

When overriding a method, you change the behavior of the method for the derived
class. Overloading a method simply involves having another method with the same
prototype.

Caution: Don't confused method overloading with method overriding, they are different,
unrelated concepts. But they sound similar.

Method overloading has nothing to do with inheritance or virtual methods.

Following are examples of methods having different overloads:

void area(int side);


void area(int l, int b);
void area(float radius);

Practical example of Method Overloading (Compile Time Polymorphism)

using System;

namespace method_overloading
{
class Program
{
public class Print
{

public void display(string name)


{
Console.WriteLine("Your name is : " + name);
}

public void display(int age, float marks)


{
Console.WriteLine("Your age is : " + age);
Console.WriteLine("Your marks are :" + marks);
}

static void Main(string[] args)


{

Print obj = new Print();


obj.display("George");
obj.display(34, 76.50f);
Console.ReadLine();
}
}
}

Note: In the code if you observe display method is called two times. Display method will
work according to the number of parameters and type of parameters.

When and why to use method overloading

Use method overloading in situation where you want a class to be able to do something,
but there is more than one possibility for what information is supplied to the method that
carries out the task.

You should consider overloading a method when you for some reason need a couple of
methods that take different parameters, but conceptually do the same thing.

Properties in C#:

In C#, properties are nothing but natural extension of data fields. They
are usually known as 'smart fields' in C# community. We know that data
encapsulation and hiding are the two fundamental characteristics of any
object oriented programming language.In C#, data encapsulation is
possible through either classes or structures. By using various access
modifiers like private, public, protected, internal etc it is possible to
control the accessibility of the class members.

Usually inside a class, we declare a data field as private and will provide a
set of public SET and GET methods to access the data fields. This is a
good programming practice, since the data fields are not directly
accessible out side the class. We must use the set/get methods to access
the data fields.
using System;
class MyClass
{
private int x;
public int X
{
get
{
return x;
}
set
{
x = value;
}
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc.X = 10;
int xVal = mc.X;
Console.WriteLine(xVal);//Displays 10
}
}

Remember that a property should have at least one accessor, either set or
get. The set accessor has a free variable available in it called value, which
gets created automatically by the compiler. We can't declare any variable
with the name value inside the set accessor.
We can do very complicated calculations inside the set or get accessor.
Even they can throw exceptions.
Since normal data fields and properties are stored in the same memory
space, in C#, it is not possible to declare a field and property with the
same name.
Static Properties

C# also supports static properties, which belongs to the class rather than
to the objects of the class. All the rules applicable to a static member are
applicable to static properties also.
The following program shows a class with a static property.
//C# : static Property
//Author: rajeshvs@msn.com
using System;
class MyClass
{
private static int x;
public static int X
{
get
{
return x;
}
set
{
x = value;
}
}
}
class MyClient
{
public static void Main()
{
MyClass.X = 10;
int xVal = MyClass.X;
Console.WriteLine(xVal);//Displays 10
}
}

Remember that set/get accessor of static property can access only other
static members of the class. Also static properties are invoking by using
the class name.
Properties & Inheritance
The properties of a Base class can be inherited to a Derived class.
//C# : Property : Inheritance
//Author: rajeshvs@msn.com

using System;
class Base
{
public int X
{
get
{
Console.Write("Base GET");
return 10;
}
set
{
Console.Write("Base SET");
}
}
}
class Derived : Base
{
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.X = 10;
Console.WriteLine(d1.X);//Displays 'Base SET Base GET 10'
}
}

The above program is very straightforward. The inheritance of properties


is just like inheritance any other member.
Properties & Polymorphism
A Base class property can be polymorphicaly overridden in a Derived
class. But remember that the modifiers like virtual, override etc are using
at property level, not at accessor level.
//C# : Property : Polymorphism
//Author: rajeshvs@msn.com
using System;
class Base
{
public virtual int X

{
get
{
Console.Write("Base GET");
return 10;
}
set
{
Console.Write("Base SET");
}
}
}
class Derived : Base
{
public override int X
{
get
{
Console.Write("Derived GET");
return 10;
}
set
{
Console.Write("Derived SET");
}
}
}
class MyClient
{
public static void Main()
{
Base b1 = new Derived();
b1.X = 10;
Console.WriteLine(b1.X);//Displays 'Derived SET Derived GET 10'
}
}

Abstract Properties
A property inside a class can be declared as abstract by using the
keyword abstract. Remember that an abstract property in a class carries
no code at all. The get/set accessors are simply represented with a
semicolon. In the derived class we must implement both set and get
assessors.

If the abstract class contains only set accessor, we can implement only set
in the derived class.
The following program shows an abstract property in action.
//C# : Property : Abstract
//Author: rajeshvs@msn.com
using System;
abstract class Abstract
{
public abstract int X
{
get;
set;
}
}
class Concrete : Abstract
{
public override int X
{
get
{
Console.Write(" GET");
return 10;
}
set
{
Console.Write(" SET");
}
}
}
class MyClient
{
public static void Main()
{
Concrete c1 = new Concrete();
c1.X = 10;
Console.WriteLine(c1.X);//Displays 'SET GET 10'
}
}

Structures in C#:
A structure in C# is simply a composite data type consisting of a number
elements of other types. A C# structure is a value type and the instances or
objects of a structure are created in stack. The structure in C# can contain
fields, methods, constants, constructors, properties, indexers, operators and
even other structure types.

Structure Declaration & Object Creation


The keyword struct can be used to declare a structure. The general form of a
structure declaration in C# is as follows.
<modifiers> struct <struct_name>
{
//Structure members
}

Where the modifier can be private, public, internal or public. The struct is the
required keyword.
For example
struct MyStruct
{
public int x;
public int y;
}

The objects of a strcut can be created by using the new operator as


follows.
MyStruct ms = new MyStruct();

The individual members of a struct can be accessed by using the dot (.)
operator as showing below.
ms.x = 10;
ms.y = 20;

Remember that unlike classes, the strcut object can also be created without
using the new operator.
MyStruct ms;

But in this case all fields of the struct will remain unassigned and the object
can't be used until all of the fields are initialized.
Structs & Fields
A struct in C# can contain fields. These fields can be declared as private,
public, internal. Remember that inside a struct, we can only declare a field.
We can't initialize a field inside a struct. However we can use constructor to
initialize the structure fields.
The following is not a valid C# struct and the code will not compile, since the
fields inside the structure are trying to initialize.
struct MyStruct
{
int x = 20; // Error its not possible to initialize
int y = 20; // Error its not possible to initialize
}

A valid C# structure is showing below.


// Author: rajeshvs@msn.com
using System;
struct MyStruct
{
public int x;
public int y;
}
class MyClient
{
public static void Main()
{
MyStruct ms = new MyStruct();
ms.x = 10;
ms.y = 20;
int sum = ms.x + ms.y;
Console.WriteLine("The sum is {0}",sum);
}
}

However a struct can contain static fields, which can be initialized inside the
struct. The following example shows the use of static fields inside a struct.
// Author: rajeshvs@msn.com
using System;

struct MyStruct
{
public static int x = 25;
public static int y = 50;
}
class MyClient
{
public static void Main()
{
int sum = MyStruct.x + MyStruct.y;
Console.WriteLine("The sum is {0}",sum);
}
}

Remember that static fields can't be accessed by an instance of a struct. We


can access them only by using the struct names.
Struct & Methods
A C# struct can also contain methods. The methods can be either static or
non-static. But static methods can access only other static members and
they can't invoke by using an object of the structure. They can invoke only
by using the struct name.
An example is shown below.
// Author: rajeshvs@msn.com
using System;
struct MyStruct
{
static int x = 25;
static int y = 50;
public void SetXY(int i, int j)
{
x = i;
y = j;
}
public static void ShowSum()
{
int sum = x + y;
Console.WriteLine("The sum is {0}",sum);
}
}
class MyClient

{
public static void Main()
{
MyStruct ms = new MyStruct();
ms.SetXY(100,200);
MyStruct.ShowSum();
}
}

The methods inside a struct can also be overloaded as like inside a class. For
example
// Author:rajeshvs@msn.com
using System;
struct MyStruct
{
static int x = 25;
static int y = 50;
public void SetXY(int i, int j)
{
x = i;
y = j;
}
public void SetXY(int i)
{
x = i;
y = i;
}
}
class MyClient
{
public static void Main()
{
MyStruct ms1 = new MyStruct();
MyStruct ms2 = new MyStruct();
ms1.SetXY(100,200);
ms2.SetXY(500);
}
}

Structs & Constructors


A C# struct can declare constrcutor, but they must take parameters. A
default constructor (constructor without any parameters) are always provided

to initialize the struct fields to their default values. The parameterized


constructors inside a struct can also be overloaded.
// Author: rajeshvs@msn.com
using System;
struct MyStruct
{
int x ;
int y ;
{ x = i; y = j;}
public MyStruct(int i)
{ x = y = i; }
public void ShowXY()
{ Console.WriteLine("The field values are {0} & {1}",x,y); }
}
class MyClient
{
public static void Main()
{
MyStruct ms1 = new MyStruct(10,20);
MyStruct ms2 = new MyStruct(30);
ms1.ShowXY();
ms2.ShowXY();
}
}

The 'this' operator can also be used in constructors and parameterized


constructors can be chained inside a C# constructor. An example is given
below.
// Author: rajeshvs@msn.com
using System;
struct MyStruct
{
int x ;
int y ;
public MyStruct(int i, int j):this(i+j)
{}
public MyStruct(int i)
{ x = y = i; }
public void ShowXY()
{ Console.WriteLine("The field values are {0} & {1}",x,y); }
}
class MyClient

{
public static void Main()
{
MyStruct ms1 = new MyStruct(10,20);
ms1.ShowXY();
}
}

Finally remember that C# struct do not support destructors.


Structs & Properties
The properties can be declared inside a struct as shown below.
//C#: Property
// Author: rajeshvs@msn.com
using System;
class MyStruct
private int x;
public int X
{
get
{
return x;
}
set
{
x = value;
}
}
}
class MyClient
public static void Main()
{
MyStruct ms = new MyStruct();
ms.X = 10;
int xVal = ms.X;
Console.WriteLine(xVal);//Displays 10
}
}

Structs & Indexers

The indexers can also be used with a C# struct. An example is shown


below.
// Author: rajeshvs@msn.com
using System;
using System.Collections;
struct MyStruct
{
public string []data ;
public string this [int index]
{
get
{
return data[index];
}
set
{
data[index] = value;
}
}
}
class MyClient
{
public static void Main()
{
MyStruct ms = new MyStruct();
ms.data = new string[5];
ms[0] = "Rajesh";
ms[1] = "A3-126";
ms[2] = "Snehadara";
ms[3] = "Irla";
ms[4] = "Mumbai";
Console.WriteLine("{0},{1},{2},{3},{4}",ms[0],ms[1],ms[2],ms[3],ms[4]);
}
}

Structs & Operator Overloading


The operators can be overloaded inside a C# structure also. The same rules
applicable with respect to a C# class is also applicable here. Both unary and
binary operators can be overloaded.
// Author: rajeshvs@msn.com
using System;

struct Complex
{
private int x;
private int y;
public Complex(int i, int j)
{
x = i;
y = j;
}
public void ShowXY()
{
Console.WriteLine("{0} {1}",x,y);
}
public static Complex operator -(Complex c)
{
Complex temp = new Complex();
temp.x = -c.x;
temp.y = -c.y;
return temp;
}
}
class MyClient
{
public static void Main()
{
Complex c1 = new Complex(10,20);
c1.ShowXY(); // displays 10 & 20
Complex c2 = new Complex();
c2.ShowXY(); // displays 0 & 0
c2 = -c1;
c2.ShowXY(); // diapls -10 & -20
}
}

Structs & Inheritance


There is no inheritance for structs as there is for classes. A struct can't
inherit from another struct or class and it can't be the base class for a class.
But remember that in C# all types are directly or indirectly inheriting from
the super base class object and hence the structure also. Since structs
doesn't support inheritance, we can't use the keywords virtual, override,
new, abstract etc with a struct methods. C# struct types are never abstract
and are always implicitly sealed. The abstract or sealed modifiers are not
permitted in a struct declaration.

Since inheritance is not supported for structs, the declared accessibility of a


struct member can't be protected or protected internal. Since all struct types
are implicitly inherit from object class, it is possible to override the methods
of the object class inside a struct by using the keyword override. Remember
that this is special case in C# structs.
Structs & Interfaces
Just like classes, a C# struct can also implement from an interface. For
example
// Author:rajeshvs@msn.com
using System;
interface IInterface
{
void Method();
}
struct Complex : IInterface
{
public void Method()
{
Console.WriteLine("Struct Method");
}
}
class MyClient
{
public static void Main()
{
Complex c1 = new Complex();
c1.Method();
}
}

Structs & Classes


The structs in C# seems to similar to classes. But they are two entirely
different aspects of the language. The classes are reference types while a
struct is a value type in C#. The objects of class types are always created on
heal while the objects of struct types are always created on the stack. But
C# structs are useful for small data structures that have value semantics.
Complex numbers, points in a co-ordinate systems etc are good examples for
struct types.

Difference between Abstraction and Encapsulation


Abstraction is "To represent the essential feature without representing the
back ground details."
Abstraction lets you focus on what the object does instead of how it does
it.
Real world Example of Abstraction: Suppose you have an object Mobile Phone.
Suppose you have 3 mobile phones as following:Nokia 1400 (Features:- Calling, SMS)
Nokia 2700 (Features:- Calling, SMS, FM Radio, MP3, Camera)
Black Berry (Features:-Calling, SMS, FM Radio, MP3, Camera, Video Recording,
Reading E-mails)
Abstract information (Necessary and Common Information) for the object "Mobile
Phone" is make a call to any number and can send SMS."
so that, for mobile phone object you will have abstract class like following:abstract class MobilePhone
{
public void Calling();
public void SendSMS();
}
public class Nokia1400 : MobilePhone
{
}
public class Nokia2700 : MobilePhone
{
public void FMRadio();
public void MP3();
public void Camera();
}
public class BlackBerry : MobilePhone
{
public void FMRadio();
public void MP3();
public void Camera();
public void Recording();
public void ReadAndSendEmails();
}

Interfaces, abstract classes or inheritance and polymorphism are tools to


provide abstraction in c#.
Encapsulation:
Wrapping up data member and method together into a single unit (i.e.
Class) is called Encapsulation.
Encapsulation is like your bag in which you can keep your pen, book etc. It
means this is the property of encapsulating members and functions.
class Bag
{
book;
pen;
ReadBook();
WriteText();
}
-Classes, properties and access modifiers are tools to provide
encapsulation in c#.

Inheritance:
When a class acquire the property of another class is known as inheritance.
Inheritance is process of object reusability.
For example, A Child acquire property of Parents.
public class ParentClass
{
public ParentClass()
{
Console.WriteLine("Parent Constructor.");
}
public void print()
{
Console.WriteLine("I'm a Parent Class.");
}
}
public class ChildClass : ParentClass
{
public ChildClass()
{
Console.WriteLine("Child Constructor.");
}
public static void Main()

{
ChildClass child = new ChildClass();
child.print();
}
}
Output:
Parent Constructor.
Child Constructor.
I'm a Parent Class.
Polymorphism:

Polymorphism means one name many forms.


One function behaves different forms.
In other words, "Many forms of a single object is called Polymorphism."

Real World Example of Polymorphism:


Example-1:
A Teacher behaves to student.
A Teacher behaves to his/her seniors.
Here teacher is an object but attitude is different in different situation.
Example-2:
Person behaves SON in house at the same time that person behaves EMPLOYEE
in office.
Example-3:
Your mobile phone, one name but many forms
As phone
As camera
As mp3 player
As radio

Constructors:
In simple terms, Constructor is a special kind of method with class name as
method name and gets executed when its (class) object is created.
Constructors can be classified into 5 types
1.
Default Constructor
2.

Parameterized Constructor

3.

Copy Constructor

4.

Static Constructor

5.

Private Constructor

Default Constructor : A constructor without any parameters is called as default


constructor. Drawback of default constructor is every instance of the class will be
initialized to same values and it is not possible to initialize each instance of the
class to different values.

Parameterized Constructor : A constructor with at least one parameter is called


as parameterized constructor. Advantage of parameterized constructor is you
can initialize each instance of the class to different values.
Copy Constructor : A parameterized constructor that contains a parameter of
same class type is called as copy constructor. Main purpose of copy constructor
is to initialize new instance to the values of an existing instance.

In simple words a copy constructor means a constructor which copies data of one object into
another object.
class employee
{
private string name;
private int age;
public employee(string name, int age) // Instance constructor.
{
this.name = name;
this.age = age;
}
public employee(employee emp) // declaring Copy constructor.
{
name = emp.name;
age = emp.age;
}
public string Details
// Get deatils of employee
{
get
{
return " The age of " + name +" is "+ age.ToString();
}
}
}
class empdetail
{
static void Main()
{
employee emp1 = new employee("Vithal", 23); // Create a new
employee object.
employee emp2 = new employee(emp1);
// here is emp1 details is
copied to emp2.
Console.WriteLine(emp2.Details);
Console.ReadLine();
}
}
}
Static Constructor : You can create a constructor as static and when a
constructor is created as static, it will be invoked only once for any number of
instances of the class and it is during the creation of first instance of the class or

the first reference to a static member in the class. Static constructor is used to
initialize static fields of the class and to write the code that needs to be executed
only once.
namespace ProgramCall
{
class Test3
{
public Test3()
{
Console.WriteLine("Instance Constructor");
}
static Test3()
{
Console.WriteLine("Static Constructor");
}
}
class StaticConstructor
{
static void Main()
{
Test3 T1 = new Test3(); // Both the constructors are invoked
Test3 T2 = new Test3(); // When this object is created only instance
constructor is invoked.
Console.Read();
}
}
}
Output Static Constructor
Instance Constructor
Instance Constructor
Private Constructor : You can also create a constructor as private. When a class
contains at least one private constructor, then it is not possible to create an
instance for the class. Private constructor is used to restrict the class from being
instantiated when it contains every member as static.

Some unique points related to constructors are as follows


A class can have any number of constructors.
A constructor doesnt have any return type even void.
A static constructor can not be a parameterized constructor.
Within a class you can create only one static constructor.

Note
A static constructor should not be declared with any access modifier.
A static constructor does not accept parameters
A static constructor is called automatically.
There is no way to call a static constructor directly.
Cant stop the execution of Static constructor

Difference between Abstract Class and Interface:


What is an Abstract Class?

An abstract class is a special kind of class that cannot be instantiated. So the


question is why we need a class that cannot be instantiated? An abstract class is
only to be sub-classed (inherited from). In other words, it only allows other
classes to inherit from it but cannot be instantiated. The advantage is that it
enforces certain hierarchies for all the subclasses. In simple words, it is a kind of
contract that forces all the subclasses to carry on the same hierarchies or
standards. The purpose of an abstract class is to provide a base class definition
for how a set of derived classes will work and then allow the programmers to fill
the implementation in the derived classes.
What is an Interface
An interface is not a class. It is an entity that is defined by the word Interface. An
interface has no implementation; it only has the signature or in other words, just
the definition of the methods without the body. As one of the similarities to
Abstract class, it is a contract that is used to define hierarchies for all subclasses
or it defines specific set of methods and their arguments. The main difference
between them is that a class can implement more than one interface but can
only inherit from one abstract class. Since C# doesn't support multiple
inheritance, interfaces are used to implement multiple inheritance.
What is an Abstract Method?
An Abstract method is a method without a body. The implementation of an
abstract method is done by a derived class. When the derived class inherits the
abstract method from the abstract class, it must override the abstract method.
This requirment is enforced at compile time and is also called dynamic
polymorphism.
abstract class test1
{
public int add(int i, int j)
{
return i+j;
}
public abstract int mul(int i, int j);
}
class test2:test1
{
public override int mul(int i, int j)
{
return i*j;
}
}
class test3:test1
{
public override int mul(int i, int j)
{
return i-j;
}
}

class test4:test2
{
public override int mul(int i, int j)
{
return i+j;
}
}
class myclass
{
public static void main (string[] args)
{
test2 ob= new test4();
int a = ob.mul(2,4);
test1 ob1= new test2();
int b = ob1.mul(4,2);
test1 ob2= new test3();
int c = ob2.mul(4,2);
Console.Write("{0},{1},{2}",a,b,c);
Console.ReadLine ();
}
}
Interfaces:
An interface looks like a class, but has no implementation. The only thing it contains are
declarations of events, indexers, methods and/or properties. The reason interfaces only
provide declarations is because they are inherited by structs and classes, that must
provide an implementation for each interface member declared.
So, what are interfaces good for if they don't implement functionality? They're great for
putting together plug-n-play like architectures where components can be interchanged at
will. Since all interchangeable components implement the same interface, they can be
used without any extra programming. The interface forces each component to expose
specific public members that will be used in a certain way.
Because interfaces must be implemented by derived structs and classes, they define a
contract.
interface IMyInterface
{
void MethodToImplement();//Abstract Method signature.
}
class InterfaceImplementer : IMyInterface
{
static void Main()
{
InterfaceImplementer obj = new InterfaceImplementer();
obj.MethodToImplement();
}
public void MethodToImplement()

{
//Abstract Method Implementation
}
}
ODDEVEN.cs

using
using
using
using

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

namespace InterFaceDemo
{
interface IOne
{
void ONE();//Pure Abstract Method Signature
}
interface ITwo
{
void TWO();
}
interface IThree:IOne
{
void THREE();
}
interface IFour
{
void FOUR();
}
interface IFive:IThree
{
void FIVE();
}
interface IEVEN:ITwo,IFour
{
}
class ODDEVEN:IEVEN,IFive//Must Implement all the abstract method, in
Derived class.
{
public void ONE()//Implementation of Abstract Method.
{
Console.WriteLine("This is ONE");
}
public void TWO()
{
Console.WriteLine("This is TWO");
}

public void THREE()


{
Console.WriteLine("This is THERE");
}
public void FOUR()
{
Console.WriteLine("This is FOUR");
}
public void FIVE()
{
Console.WriteLine("This is FIVE");
}
}
}
Program.cs

using
using
using
using

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

namespace InterFaceDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("This is ODD");
IFive obj1 = new ODDEVEN();
obj1.ONE();
obj1.THREE();
obj1.FIVE();
Console.WriteLine("\n\nThis is EVEN");
IEVEN obj2 = new ODDEVEN();
obj2.TWO();
obj2.FOUR();
Console.ReadLine();
}
}
}
The following is the output:

Implicit & Explicit Interfaces:

Purposes of Interfaces

1. Create loosely coupled software.


2. Support design by contract (an implementer must provide the entire interface).
3. Allow for pluggable software.
4. Allow objects to interact easily.
5. Hide implementation details of classes from each other.
6. Facilitate reuse of software.
Example 1
interface Iinterface_1
{
}
class Class1 : Iinterface_1
{
public void Display()
{
Console.WriteLine("Class1 Display Method.");
}
}
class Program
{
static void Main(string[] args)
{
Class1 objClass1 = new Class1();
objClass1.Display();
}
}

Output: Class1 Display Method


Example 2
The following is an example of Implicit and Explicit interface implementation:
interface Iinterface_1
{
void interface1_method();
}
class Class1 : Iinterface_1
{
public void Display()
{
Console.WriteLine("Class1 Display Method.");
}
//Implicit interface implementation
public void interface1_method()
{
Console.WriteLine("Iinterface_1 Method.");
}

//Explicit interface implementation


void Iinterface_1.interface1_method()
{
Console.WriteLine("Iinterface_1 Method.");
}

class Program
{
static void Main(string[] args)
{
Class1 objClass1 = new Class1();
objClass1.Display();
}
}

Output: Class1 Display Method.


Example 3
The following is an example of how to call an Implicit interface method:
interface Iinterface_1
{
void interface1_method();
}
class Class1 : Iinterface_1

{
public void Display()
{
Console.WriteLine("Class1 Display Method.");
}
//Implicit interface implementation
public void interface1_method()
{
Console.WriteLine("Iinterface_1 Method Implicit interface implementation.");
}
//Explicit interface implementation
void Iinterface_1.interface1_method()
{
Console.WriteLine("Iinterface_1 Method Explicit interface implementation.");
}
}
class Program
{
static void Main(string[] args)
{
Class1 objClass1 = new Class1();
objClass1.Display();
//Call Implicit interface method
objClass1.interface1_method();
Console.ReadLine();
}
}
Output: Class1 Display Method.
Iinterface_1 Method Implicit interface implementation.

Note:

In the picture above, when you type objClass1., then only interface1_method will be

shown and Iinterface_1.interface1_method is not found.


So you can't call explicit interface from class object. (i.e objClass1)
Example 4
The following is an example of how to call an explicit interface method.
interface Iinterface_1
{
void interface1_method();
}
class Class1 : Iinterface_1
{
public void Display()
{
Console.WriteLine("Class1 Display Method.");
}
//Implicit interface implementation
public void interface1_method()
{
Console.WriteLine("Iinterface_1 Method Implicit interface implementation.");
}

//Explicit interface implementation


void Iinterface_1.interface1_method()
{
Console.WriteLine("Iinterface_1 Method Explicit interface implementation.");
}

class Program
{
static void Main(string[] args)
{
Class1 objClass1 = new Class1();
objClass1.Display();
//Call Implicit interface method
objClass1.interface1_method();
//Call Explicit interface method
Iinterface_1 obj_1 = new Class1();
obj_1.interface1_method();
Console.ReadLine();
}
}
Output: Class1 Display Method.
Iinterface_1 Method Implicit interface implementation.
Iinterface_1 Method Explicit interface implementation.

Delegates:
There might be situation in which you want to pass methods around to other methods.
For this purpose we create delegate.
A delegate is a class that encapsulates a method signature. Although it can be used in
any context, it often serves as the basis for the event-handling model in C# but can be
used in a context removed from event handling (e.g. passing a method to a method
through a delegate parameter).

A Delegate Usage Example


namespace MyFirstDelegate
{
//This delegate can point to any method,
//taking two integers and returning an
//integer.
public delegate int MyDelegate(int x, int y);
//This class contains methods that MyDelegate will point to.
public class MyClass
{
public static int Add(int x, int y)
{
return x + y;
}
public static int Multiply(int x, int y)
{
return x * y;
}
}
class Program
{
static void Main(string[] args)
{
//Create an Instance of MyDelegate
//that points to MyClass.Add().
MyDelegate del1 = new MyDelegate(MyClass.Add);
//Invoke Add() method using the delegate.
int addResult = del1(5, 5);
Console.WriteLine("5 + 5 = {0}\n", addResult);
//Create an Instance of MyDelegate
//that points to MyClass.Multiply().
MyDelegate del2 = new MyDelegate(MyClass.Multiply);
//Invoke Multiply() method using the delegate.

int multiplyResult = del2(5, 5);


Console.WriteLine("5 X 5 = {0}", multiplyResult);
Console.ReadLine();
}
}
}

Delegate ability to Multicast


Delegate's ability to multicast means that a delegate object can maintain
a list of methods to call, rather than a single method
if you want to add a method to the invocation list of a delegate object ,
you simply make use of the overloaded += operator, and if you want to
remove a method from the invocation list you make use of the overloaded
operator -= .
Note: The Multicast delegate here contain methods that return void, if
you want to create a multicast delegate with return type you will get the
return type of the last method in the invocation list.
A Multicast Delegate Example
namespace MyMulticastDelegate
{
//this delegate will be used to call more than one
//method at once
public delegate void MulticastDelegate(int x, int y);
//This class contains methods that MyDelegate will point to.
public class MyClass
{
public static void Add(int x, int y)
{
Console.WriteLine("You are in Add() Method");
Console.WriteLine("{0} + {1} = {2}\n", x, y, x + y);
}
public static void Multiply(int x, int y)
{
Console.WriteLine("You are in Multiply() Method");
Console.WriteLine("{0} X {1} = {2}", x, y, x * y);
}
}
class Program
{
static void Main(string[] args)

{
//Create an Instance of MulticastDelegate
//that points to MyClass.Add().
MulticastDelegate del = new MulticastDelegate(MyClass.Add);
//using the same instance of MulticastDelegate
//to call MyClass.Multibly() by adding it to it's
//invocation list.
del += new MulticastDelegate(MyClass.Multiply);
//Invoke Add() and Multiply() methods using the delegate.
//Note that these methods must have a void return vlue
Console.WriteLine("****calling Add() and Multibly() Methods.****\n\n");
del(5, 5);
//removing the Add() method from the invocation list
del -= new MulticastDelegate(MyClass.Add);
Console.WriteLine("\n\n****Add() Method removed.****\n\n");
//this will invoke the Multibly() method only.
del(5, 5);
}
}
}

EVENTS:
Windows based applications are message based. Application is communicating with
windows and windows are communicating with application by using predefined
messages. .Net wraps up the messages with 'EVENTS'. And .Net reacting a particular
message by handling events. Events are the message sent by an object to indicate the
occurrence of an event. Event can also be defined as a member that enables an object
to provide notification. Events provide a powerful means of inter-process
communication. Events are used for communication between Objects. Communication
between Objects is done by events.
Delegates are used as the means of wiring up the event when the message is received
by the application.

Event Receiver
The event receiver may be

1. An application
2. An Object
3. A component
Event receiver gets modified when something happens.
Event Sender
The Event sender may be

1. An assembly in an application
2. An object
3. System events like Mouse event or keyboard entry.
Event sender's job is to raise the Event. Event sender doesn't know anything about,
whom and what the receiver is. To handle the event, there would be some method
inside event receiver. This Event handler method will get executed each time when
event is registered to be raised.
Here DELEGATE comes into action, because Sender has no idea who the
receiver will be.
The PROCESS of hooking up the event handler is known as WIRING UP an
Event.
A simple example of wiring up is CLICK EVENT.
The EventHandler Delegate
This Delegate is defined in .Net framework. It is defined in System namespace. All of the
events that are defined in .Net framework will use it.

1. EventHandler cannot return any value, so it should return Void.


2. Parameters are Object and EventArgs
3. The first parameter is an Object that raises the Event.
4. The Second parameter is EventArgs. This contains information about the Event.
Example:
Private void Button_Click(Object sender, EventArgs e)
{
}
Here first parameter is a Button; this could be any button if there are multiple buttons
on form.
The Second parameter is EventArags. This mainly contains the property for which Button
is used.
Example 1:
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace EventExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Adding EventHandler to Click event of Buttons
btn1.Click +=new EventHandler(Button_Click);
btn2.Click +=new EventHandler(Button_Click);
}
// Button Click Method , here signature of this is same as of Eventhandler
private void Button_Click(Object sender, EventArgs e)
{
string str;
if (sender == btn1)
{
str = btn1.Text;
MessageBox.Show(str+" Clicked ");
}
if (sender == btn2)
{
str = btn2.Text;

MessageBox.Show(str+ " Clicked ");

}
}

CUSTOM EXCEPTION HANDLING:

Creating User-Defined Exceptions


You can also define your own exception. User-defined exception classes
are derived from the Exception 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: Exception


{

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

ENUMS:
What is enum?
An enum is a value type with a set of related named constants often referred to as an
enumerator list. The enum keyword is used to declare an enumeration. It is a primitive
data type, which is user defined.
Enums type can be integer (float, int, byte, double etc.). But if you used beside int it has
to becast.

enum is used to create numeric constants in .NET framework. All member of enum are of
enum type. There must be a numeric value for each enum type.
The default underlying type of the enumeration elements is int. By default, the first
enumerator has the value 0, and the value of each successive enumerator is increased
by 1.
enum Dow {Sat, Sun, Mon, Tue, Wed, Thu, Fri};
Program to demonstrate how to create and Use an Enum:
using System;
namespace example_enum
{
class Program
{
public enum DayofWeek
{
Sunday = 1, Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday
}
static void Main(string[] args)
{
Console.WriteLine("Day of week {0} {1}",
(int)DayofWeek.Sunday,DayofWeek.Sunday);
Console.WriteLine("Day of week {0} {1}",
(int)DayofWeek.Monday,DayofWeek.Monday);
Console.WriteLine("Day of week {0} {1}",
(int)DayofWeek.Tuesday,DayofWeek.Tuesday);
Console.WriteLine("Day of week {0} {1}",
(int)DayofWeek.Wednesday,DayofWeek.Wednesday);
Console.WriteLine("Day of week {0} {1}",
(int)DayofWeek.Thursday,DayofWeek.Thursday);
Console.WriteLine("Day of week {0} {1}",
(int)DayofWeek.Friday,DayofWeek.Friday);
Console.WriteLine("Day of week {0} {1}",
(int)DayofWeek.Saturday,DayofWeek.Saturday);
Console.ReadLine();
}
}
}

Some points about enum:

enums are enumerated data type in c#.

enums are not for end-user, they are meant for developers.

enums are strongly typed constant. They are strongly typed, i.e. an enum of one
type may not be implicitly assigned to an enum of another type even though the
underlying value of their members are the same.

Enumerations (enums) make your code much more readable and understandable.

enum values are fixed. enum can be displayed as a string and processed as an
integer.

The default type is int, and the approved types are byte, sbyte, short, ushort,
uint, long, and ulong.

Every enum type automatically derives from System.Enum and thus we can use
System.Enum methods on enums.

Enums are value types and are created on the stack and not on the heap.

You give two same values in enum type?


Yes we can have same value in enum type. Example when we want to set priority options
like
Normal

Excellent

Default

Good

ACCESS MODIFIERS:
Why to use access modifiers?

Access modifiers are an integral part of object-oriented programming. They support the
concept of encapsulation, which promotes the idea of hiding functionality. Access
modifiers allow you to define who does or doesn't have access to certain features.

In C# there are 5 different types of Access Modifiers.

Modifier

Description

public

There are no restrictions


on accessing public
members.

private

Access is limited to within


the class definition. This is
the default access modifier
type if none is formally
specified

protected

Access is limited to within


the class definition and
any class that inherits
from the class

internal

Access is limited
exclusively to classes
defined within the current
project assembly

protected

Access is limited to the

internal

current assembly and


types derived from the
containing class. All
members in current
project and all members in
derived class can access
the variables.

ATTRIBUTES:

What is an attributes ?
An attribute is a information which marks the elements of code such as a class or

method. For example .NET framework provides the system.obsoleteAttribute


attribute which can be used to mark a method as follows[we use [] brackets to attach
attributes to code elements]
[System.ObsoleteAttribute()]
void Fun{}

The Fun method is marked with the system.ObsoleteAttribute attribute information is


inserted in the assembly during compilation. This information then can be used by
the c# compiler. When it encounters a call to method, it can then emit a warning
indicating it is better to avoid call to an obsolete method, which risks of going away in
future versions. Without an attribute, you would be forced to properly document the
fact that Fun() method is now obsolete the weakness of this approach is that you will
have no guarantee that your clients will read the documentation and be aware of the
fact that method is now obsolete.

REFLECTION:

Introduction
In C#, Reflection is a process by which we can get the detailed information from
assembly, like about method, constructor, attribute, property, module, global class,
parameters, and many more at run time. Reflection can modify structure and behavior of
a computer program.
What is Reflection in C#
"Reflection is a mechanism by which we can get metadata information from assembly at
run time."
When use Reflection
If we want to know assembly information at run time ,then we use reflection. Reflection
are used for data binding in .NET Framework. It is also used for testing in .NET
Framework.
How to use
There are System.Reflection is the namespace for the reflection. System.Reflection
namespace defines the assembly module, MemberInfo, PropertyInfo, MethodInfo,
ConstructorInfo, FieldInfo, EventInfo etc.
The System.Type is the base class for reflection. System.Type find the type name,
namespace, module type etc. System.Type is also an abstract class .
using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
namespace reflection
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
int n = 45;
//string n = "vineet";
System.Type t = n.GetType();
MessageBox.Show(t.ToString());//Display type of varible
MessageBox.Show(t.Name);//Display name of variable
MessageBox.Show(t.Namespace);//Display namespace by name
MessageBox.Show(t.IsArray.ToString());//Display boolean value
MessageBox.Show(t.IsClass.ToString());//Display boolean value
MessageBox.Show(t.Module.ToString());//Display module(library) of assembly
MessageBox.Show(t.MemberType.ToString());//Display membertype by name
MessageBox.Show(t.GetProperties().ToString());//Display property by name
MessageBox.Show(t.GetType().ToString());//Display type defined in assembly
MessageBox.Show(t.GetMethods().ToString());//Display method by name
MessageBox.Show(t.GetInterfaces().ToString());//Display interface by name
MessageBox.Show(t.FullName.ToString());//Display type of variable by name
MessageBox.Show(t.BaseType.ToString());//Display base type
MessageBox.Show(t.Attributes.ToString());//Display attribute by name
MessageBox.Show(t.Assembly.ToString());//Display assembly by name
MessageBox.Show(t.AssemblyQualifiedName.ToString());//Display
AssemblyQualifiedName
System.Reflection.Assembly o =
System.Reflection.Assembly.Load("mscorlib.dll");
MessageBox.Show(o.GetName().ToString());//Display information
about mscorlib assembly
object obj = o.GetType();
MessageBox.Show(obj.ToString());//Display name of runtime assembly
ConstructorInfo[] ci = t.GetConstructors();//Display information about
constructors
foreach (ConstructorInfo i in ci)
{
MessageBox.Show(i.ToString());
}
MethodInfo[] mi = t.GetMethods();//Display information about methods
foreach (MethodInfo i in mi)

{
MessageBox.Show(i.ToString());
}
PropertyInfo[] pi = t.GetProperties();//Display information about properties
foreach (PropertyInfo i in pi)
{
MessageBox.Show(i.ToString());
}
MemberInfo[] mf = t.GetMembers();//Display information about members
foreach (MemberInfo i in mf)
{
MessageBox.Show(i.ToString());
}
EventInfo[] ei = t.GetEvents();//Display information about events
foreach (EventInfo i in ei)
{
MessageBox.Show(i.ToString());
}
FieldInfo[] fi= t.GetFields();//Display information about fields
foreach (FieldInfo i in fi)
{
MessageBox.Show(i.ToString());
}
}
}
}

COLLECTIONS:

Introduction
It is just like as array ,but always dynamic and can hold any values unlike array. It is a
data structure that holds data in many different ways. The collection class is defined in
the System.Collections namespace. There are five types of collections in data structure.
1.Hastable
2.Arraylist
3.Linkedlist
4.Stack
5.Queue
But mostly use of two types collections in C#,they are Hastable and Arraylist. Here we
will discuss about only Hastable and Arraylist.
1. Hastable
Hastable have two values i.e. key(id) and item(value).

Why we use Hastable


If we want to stored data in two dimensional array at run time then we use Hastable.
For example, a months name and his serial number and we can access there data using
a key.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
namespace hastable
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Hashtable hs = new Hashtable();
hs.Add("1", "January");
hs.Add("2", "Febuary");
hs.Add("3", "March");
hs.Add("4", "April");
hs.Add("5","May");
hs.Add("6", "june");
hs.Add("7", "July");
hs.Add("8", "August");
hs.Add("9", "September");
hs.Add("10", "October");
hs.Add("11", "November");
hs.Add("12", "December");
//MessageBox.Show(hs["8"].ToString());// print one value(August)
foreach (string k in hs.Keys)
{
MessageBox.Show(hs[k].ToString());//print all values
}
}
}
}

Now run the application.


Output (One value using key) looks like the below image.

Output (all values using foreach loop) looks like the below image.

code description
In the above code first of all we make the object of hastable i.e. hs. After that we add
the key and value using the hs object in the hastable. If we print the only one value then
we will give your key(id), which is shown above. If we print the all values then we use
foreach loop.
2. ArrayList
Arraylist have only one values i.e. item(value) not a key(id).

Why we use ArrayList


We know that array have a fixed size. If we want to add items beyond the specified
dimension then we use Arraylist. If we want to insert an item in a list then we use Linked
list but in the C# we use Arraylist for that purpose.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
namespace arraylist
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ArrayList al = new ArrayList();
al.Add("January");
al.Add("Febuary");
al.Add("March");
al.Add("April");
al.Add("May");
al.Add("june");
al.Add("July");
al.Add("August");
al.Add("September");
al.Add("October");
al.Add("November");
al.Add("December");
//MessageBox.Show(al[0].ToString());//Print the one value
foreach (string k in al)
{
MessageBox.Show(k.ToString());// Print the all values
}
}
}
}

Now run the application.


Output (One value using index number) looks like the below image.

Output (all values using foreach loop) looks like the below image.

0
code description
In the above code first of all we make the object of Arraylist i.e. 'al'. After that we add
the value using the 'al' object in the Arraylist. If we print the only one value then we will
give index number, which is shown above. If we print the all values then we use foreach
loop.
Summary

Collections are very important for stored data in the array and list. Collections solves the
many problem like as fixed array ,linked list etc. So collections are very useful for solving
these problems.

GENERICS:

Introduction:
Generics give you the ability to create generic methods or a generic type by
defining a placeholder for method arguments or type definitions, that are
specified at the time of invoking the generic method or creating the generic
type.
Why Generics?

To understand the importance of generics let's start by seeing some kind of


problems that can be solved by them.
ArrayList:
Let's start by creating an ArrayList to hold stack-allocated data.
ArrayList intList = new ArrayList();

As you may know, the ArrayList collection can receive and return only an
Object type, so the runtime will convert the value type (stack-allocated)
automatically via boxing operation into an Object (heap-allocated) as in the
following:
ArrayList intList = new ArrayList();
//add a value type to the collection(boxing)

intList.Add(5);
To retrieve the value from the ArrayList you must unbox the heap-allocated
object into a stack-allocated integer using a casting operation.
//unboxing
int x = (int)intList[0];

The problem with the stack/heap memory transfer is that it can have a big
impact on performance of your application because when you use boxing and
unboxing operations the following steps occur:
1. A new object must be allocated on the managed heap.
2. The value of the stack-allocated type must be transferred into that
memory location.

3. When unboxed, the value stored on the heap must be transferred back
to the stack.
4. The unused object on the heap will be garbage collected.

Now consider that your ArrayList contained thousands of integers that are
manipulated by your program, this for sure will have an affect on your
application performance.
Custom Collections:
Assume that you need to create a custom collection that can only contain
objects of the Employee type.

public class Employee


{
string FirstName;
string LastName;
int Age;
public Employee(){}
public Employee(string fName, string lName, int Age)
{
this.Age = Age;
this.FirstName = fName;
this.Lastname = lName;
}
public override string ToString()
{
return String.Format("{0} {1} is {2} years old", FirstName, LastName, Age);
}
}

Now we will build the custom collection as in the following:


public class EmployeesCollection : IEnumerable
{
ArrayList alEmployees = new ArrayList();
public EmployeesCollection() { }
//Insert Employee type
public void AddEmployee(Employee e)

{
//boxing
alEmployees.Add(e);
}
//get the employee type
public Employee GetEmployee(int index)
{
//unboxing
return (Employee)alEmployees[index];
}
//to use foreach
IEnumerator IEnumerable.GetEnumerator()
{
return alEmployees.GetEnumerator();
}
}

The problem here is that if you have many types in you application then you
need to create multiple custom collections, one for each type. And as you can
see, we also have the problem of boxing and unboxing here.
All problems you saw previously can be solved using generics, so let's see
what we can do.
The System.Collections.generic namespace
You can find many generic collections in the System.Collections.Generic just
like:
1. List<T>
2. Dictionary<K, V>
3. Queue<T>
4. Stack<T>
Generic collections allow you to delay the specification of the contained type
until the time of creation.
By using the generic collection you avoid performance problems of the
boxing and unboxing operations and don't need to create a custom collection

for each type in you application.


With the generic collections it's up to you to define the type that will be
contained in the collection by replacing the placeholder T by the type you
want at the time of creation.
List<T>
The List<T> is a generic collection that represents a strongly typed list of
objects that can be accessed by index. It is just like the non-generic
collection ArrayList.
The following is an example of a List<T>:
//Can only contain int type
List<int> intList = new List<int>();
//no boxing
intList.Add(10);
//no unboxing
int x = intList[0];
//Can only contain Employee objects
List<Employee> empList = new List<Employee>();
//no boxing
empList.Add(new Employee("Amr", "Ashush", 23));
//no unboxing
Employee e = empList[0];

Queue<T>
Queue<T> is a generic collection that represents a first-in, first-out (FIFO)
collection of objects. It is just like the non-generic collection Queue.
The following is an example of a Queue<T>:
//A generic Queue collection
Queue<int> intQueue = new Queue<int>();
//Add an int to the end of the queue
//(no boxing)
intQueue.Enqueue(5);

//Returns the int at the beginning of the queue


//without removing it.
//(no unboxing)
int x = intQueue.Peek();
//Removes and returns the int at the beginning of the queue
//(no unboxing)
int y = intQueue.Dequeue();

Stack<T>
Stack<T> is a generic collection that represents a last-in-first-out (LIFO)
collection of instances of the same arbitrary type. It is just like the nongeneric collection Stack.
The following is an example of a Stack<T>:
Stack<int> intStack = new Stack<int>();
//Insert an int at the top of the stack
//(no boxing)
intStack.Push(5);
//Returns the int at the top of the stack
//without removing it.
//(no unboxing)
int x = intStack.Peek();
//Removes and returns the int at the top of the stack
//(no unboxing)
int y = intStack.Pop();

Dictionary<K, V>
Dictionary<K, V> is a generic collection that contains data in Key/Value
pairs, it is just like the non-generic collection Hashtable.
The following is an example of a Dictionary<K, V>:
Dictionary<string, string> dictionary = new Dictionary<string, string>();
//Add the specified key and value to the dictionary
dictionary.Add("Key", "Value");

//Removes the value with the specified key from the dictionary
dictionary.Remove("Key");
//get the number of the Key/Value pairs contained in the dictionary
int count = dictionary.Count;

BOXING AND UNBOXING:

Boxing
Implicit conversion of a value type (int, char etc.) to a reference type (object), is
known as Boxing. In boxing process, a value type is being allocated on the heap
rather than the stack.

Unboxing
Explicit conversion of same reference type (which is being created by boxing
process); back to a value type is known as unboxing. In unboxing process, boxed
value type is unboxed from the heap and assigned to a value type which is being
allocated on the stack.

For Example
1. // int (value type) is created on the Stack
2. int stackVar = 12;
3.
4. // Boxing = int is created on the Heap (reference type)
5. object boxedVar = stackVar;
6.
7. // Unboxing = boxed int is unboxed from the heap and assigned to an int
stack variable
8. int unBoxed = (int)boxedVar;

Real Life Example

1. int i = 10;
2. ArrayList arrlst = new ArrayList();
3.
4. //ArrayList contains object type value
5. //So, int i is being created on heap
6. arrlst.Add(i); // Boxing occurs automatically
7.
8. int j = (int)arrlst[0]; // Unboxing occurs

DIFFERENCE BETWEEN STRING AND STRING BUILDER:

String
String is immutable, Immutable means if you create string object then you cannot
modify it and It always create new object of string type in memory.
Example
string strMyValue = "Hello Visitor";
// create a new string instance instead of changing the old one
strMyValue += "How Are";
strMyValue += "You ??";
Stringbuilder
StringBuilder is mutable, means if create string builder object then you can perform any
operation like insert, replace or append without creating new instance for every time.it
will update string at one place in memory doesnt create new space in memory.
Example
StringBuilder sbMyValue = new StringBuilder("");
sbMyValue.Append("Hello Visitor");
sbMyValue.Append("How Are You ??");
string strMyValue = sbMyValue.ToString();
PARTIAL CLASSES:
It is possible to split the definition of a class or a struct, or an interface over two or more
source files. Each source file contains a section of the class definition, and all parts are
combined when the application is compiled.

When working on large projects, spreading a class over separate files allows multiple
programmers to work on it simultaneously.
When working with automatically generated source, code can be added to the class
without having to recreate the source file. Visual Studio uses this approach when
creating Windows Forms, Web Service wrapper code, and so on. You can create code
that uses these classes without having to edit the file created by Visual Studio.

Example
I will develop an example that explains how to use a partial class in your project. Suppose
you are working with LINQ to SQL in your application. So you create a data context, in
other words a .dbml file and drag and drop the necessary tables. Each table creates a
partial class in the data context designer file and each table field becomes a property for
the table. Suppose you have a "Person" table that has the three fields "Id","Name" and
"DateOfBirth" and you want to show the age of each person in a grid view. What will you
do? If you add a new column to the table for age in database for the "Person" table then
it fails the normalization rule so you should not do that. If you add a new property to
auto-generated code then it will not be mapped to the database. So you need to create a
partial class portion in a separate source file that has the "Age" property. This "Age"
property calculates the age of the person when you bind a person list to the grid view.
Let's see each step-by-step.

1. Create a "Person" table in the database.


You need to create a person table in the database that has the three fields
"Id","Name" and "DateOfBirth". The "Id" field is the primary key.
CREATETABLE Person
(
Idint identity(1,1)primary key,
Namenvarchar(50),
DateOfBirthDate defaultgetUtcDate()
)

2. Create a web application from Visual Studio.

3. Right-click on the project in the Solution Explorer then go to "Add" and click on
"Class".

4. Choose "LINQ to SQL Classes" from the list and provide the name "Person" for the
DBML name. Then click on "Add".

5. Drag the User table from the database in the Server Explorer and drop onto the
O/R Designer surface of the "Person.dbml" file.

Figure 1.2: Person entity


Now you can open the "Person.designer.cs" file. In the file the "Person" partial
class has been created for drag and drops a "Person" table from database on
O/RM surface.

6. Create a partial class part that has the "Age" property to calculate the age. This
file is named "PersonExtension.cs".

using System;
namespace PartialClassExample
{
public partialclass Person
{
public int Age
{
get { returnConvert.ToInt32(System.DateTime.UtcNow.Date.Year _DateOfBirth.Value.Year); }
}
}
}

7. Create a UI design to show a person's details in the grid view.

<
%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="PersonUI.aspx.cs"
Inherits="PartialClassExample.PersonUI"%>
<!DOCTYPEhtml>
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headid="Head1"runat="server">
<title></title>

</head>
<body>
<formid="form1"runat="server">
<div>
<asp:GridViewID="gridPerson"runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>

8. Write code for the "Page_Load" event to bind a grid view by person list in the code
behind file.

using System;
using System.Linq;
namespace PartialClassExample
{
public partialclass PersonUI : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (PersonDataContext context =new PersonDataContext())
{
var query = from person in context.GetTable<Person>()
select new
{
person.Id,
person.Name,
person.DateOfBirth,
person.Age
};
var content = query.ToList();
gridPerson.DataSource = content;
gridPerson.DataBind();
}
}
}
}

9. Run the application, you will see the Age column in the grid view that shows the
age of each person. Let's see that in Figure 1.3.

INDEXERS
Indexer allows classes to be used in more intuitive manner. C# introduces a new concept
known as Indexers which are used for treating an object as an array. The indexers are
usually known as smart arrays in C#. They are not essential part of object-oriented
programming.
An indexer, also called an indexed property, is a class property that allows you to access
a member variable of a class using the features of an array.
Defining an indexer allows you to create classes that act like virtual arrays. Instances of
that class can be accessed using the [] array access operator.
Creating an Indexer
<modifier> <return type> this [argument list]
{
get
{
// your get block code
}
set
{
// your set block code
}
}
In the above code:
<modifier>
can be private, public, protected or internal.

<return type>
can be any valid C# types.
this
this is a special keyword in C# to indicate the object of the current class.
[argument list]
The formal-argument-list specifies the parameters of the indexer.
Important points to remember on indexers:

Indexers are always created with this keyword.

Parameterized property are called indexer.

Indexers are implemented through get and set accessors for the [ ] operator.

ref and out parameter modifiers are not permitted in indexer.

The formal parameter list of an indexer corresponds to that of a method and at


least one parameter should be specified.

Indexer is an instance member so can't be static but property can be static.

Indexers are used on group of elements.

Indexer is identified by its signature where as a property is identified it's name.

Indexers are accessed using indexes where as properties are accessed by names.

Indexer can be overloaded.

Indexer are defined in pretty much same way as properties, with get and set functions.
The main difference is that the name of the indexer is the keyword this.
Following program demonstrate how to use indexer.
using System;
namespace Indexer_example1
{
class Program
{
class IndexerClass

{
private string[] names = new string[10];
public string this[int i]
{
get
{
return names[i];
}
set
{
names[i] = value;
}
}
}
static void Main(string[] args)
{
IndexerClass Team = new IndexerClass();
Team[0] = "Rocky";
Team[1] = "Teena";
Team[2] = "Ana";
Team[3] = "Victoria";
Team[4] = "Yani";
Team[5] = "Mary";
Team[6] = "Gomes";
Team[7] = "Arnold";
Team[8] = "Mike";
Team[9] = "Peter";
for (int i = 0; i < 10; i++)
{
Console.WriteLine(Team[i]);
}
Console.ReadKey();
}
}
}

Difference between Indexers and Properties


Indexers

Properties

Indexers are created with this

keyword.

Indexers are identified by signature.

Properties don't require this


keyword.

Properties are identified by their


names.

Indexers are accessed using

indexes.

Indexer are instance member, so

names.

can't be static.

A get accessor of an indexer has the

Properties are accessed by their

Properties can be static as well as


instance members.

same formal parameter list as the

A get accessor of a property has no


parameters.

indexer.

A set accessor of an indexer has the

A set accessor of a property

same formal parameter list as the

contains the implicit value

indexer, in addition to the value

parameter.

parameter.

Indexers are commonly used for classes, which represents some data structure, an
array, list, map and so on.

SEALED CLASS & SEALED METHODS:


Sealed Class

Sealed class is used to define the inheritance level of a class.

The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is
specified as the base class of another class.

Some points to remember:

1. A class, which restricts inheritance for security reason is declared, sealed class.
2. Sealed class is the last class in the hierarchy.
3. Sealed class can be a derived class but can't be a base class.

4. A sealed class cannot also be an abstract class. Because abstract class has to
provide functionality and here we are
restricting it to inherit.
Practical demonstration of sealed class

using
using
using
using

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

namespace sealed_class
{
class Program
{
public sealed class BaseClass
{
public void Display()
{
Console.WriteLine("This is a sealed class which can;t be further
inherited");
}
}
public class Derived : BaseClass
{
// this Derived class can;t inherit BaseClass because it is sealed
}
static void Main(string[] args)
{
BaseClass obj = new BaseClass();
obj.Display();
Console.ReadLine();
}
}
}
Sealed Methods
Sealed method is used to define the overriding level of a virtual method.
Sealed keyword is always used with override keyword.
Practical demonstration of sealed method
using System;
using System.Collections.Generic;

using System.Linq;
using System.Text;
namespace sealed_method
{
class Program
{
public class BaseClass
{
public virtual void Display()
{
Console.WriteLine("Virtual method");
}
}
public class DerivedClass : BaseClass
{
// Now the display method have been sealed and can;t be overridden
public override sealed void Display()
{
Console.WriteLine("Sealed method");
}
}
//public class ThirdClass : DerivedClass
//{
//
//
//
which is
//
//}

public override void Display()


{
Console.WriteLine("Here we try again to override display method
not possible and will give error");
}

static void Main(string[] args)


{
DerivedClass ob1 = new DerivedClass();
ob1.Display();
Console.ReadLine();
}
}
}

FILE I/O :

File handling is a very crucial and important feature for many enterprise applications
around us. To support this feature Microsoft .NET Framework offers the System.IO
namespace, that provides various classes to enable the developers to do I/O.
In this article, you will learn how to work with classes in the System.IO namespace for
reading data from and writing data to files. The System.IO namespace also provides
features to support manipulation of files and directories of the operating systems file
system.
Objectives

Using the File class for reading and writing data.

Using the File and FileInfo class to manipulate files.

Using the DirectoryInfo and Directory classes to manipulate directories.

Using the File class for reading and writing data.


The File class of the System.IO namespace offers various static methods that enable a
developer to do direct reading and writing of files. Typically, to read data from a file, you:
1. Get a hold on the file handle.
2. Open a stream to the file.
3. Buffer the file data into memory.
4. Release the hold of file handle once done.
Reading Data from Files
The following list describes some of these methods:

The "ReadAllText" method reads the data of a file.

string filePath = @"C:\MyData\TestFile.txt";


string testData = File.ReadAllText(filePath);

The "ReadAllLines" method reads all the contents of a file and stores each line at
a new index in an array of string type.

string filePath = @"C:\MyData\TestFile.txt";

string[] testDataLineByLine = File.ReadAllLines(filePath);

The "ReadAllBytes" method reads the contents of a file as binary data and stores
the data in a byte array.
string filePath = @"C:\MyData\TestFile.txt";
byte[] testDataRawBytes = File.ReadAllBytes(filePath);

Each of these methods enable the developer to read the contents of a file and load into
memory. The ReadAllText method will enable the developer to cache the entire file in
memory via a single operation. Whereas the ReadAllLines method will read line-by-line
into an array.
Writing Data to Files
The File class also provides methods for writing various types of data to a file. For each
of the various types of data you can write, the File class provides two methods. If the
specified file does not exist, then the Writexxx methods create a new file with the new
data. If the file does exist then the Writexxx methods overwrite the existing file with the
new data. If the specified file does not exist then the Appendxxx methods also create a
new file with the new data.
However, if the file does exist then the new data is written to the end of the existing file.
The following list describes some of these methods:

The "WriteAllText" method enables the developers to write the contents of string
variable into a file. If the file exists, its contents will be overwritten. The following
code example shows how to write the contents of a string named settings to a
new file named settings.txt.
string filePath = @"C:\MyData\TestFile.txt";
string data = "C# Corner MVP & Microsoft MVP;";
File.WriteAllText(filePath, data);

The "WriteAllLines" method enables the developers to write the contents of a


string array to a file. Each entry in the string array will be a new line in the new
file.
string filePath = @"C:\MyData\TestFile.txt";
string[] data = { "MCT", "MCPD", "MCTS", "MCSD.NET", "MCAD.NET", "CSM" };
File.WriteAllLines(filePath, data);

The "AppendAllText" method enables the developers to write the contents of a


string variable at the end of an existing file.
string filePath = @"C:\MyData\TestFile.txt";
string data = "Also Certified from IIT Kharagpur";
File.AppendAllText(filePath, data);

The "AppendAllLines" method enables the developers to write the contents of a


string array to the end of an existing file.
string filePath = @"C:\MyData\TestFile.txt";
string[] otherData = { "Worked with Microsoft", "Lived in USA" };
File.AppendAllLines(filePath, otherData);

File and FileInfo class to Manipulating Files


File manipulation is as important as file creation. Many applications typically require the
ability to interact with files stored on the file system. For example, copying a file from a
directory to another location for further processing.
Developers can implement this type of functionality by using the File and FileInfo
classes.
Using File class to manipulate files
The File class consists of various static methods that a developer can use to perform
basic file manipulation. The following list describes some of those methods.
The "Copy" method enables the developers to copy an existing file to a different
directory location on the file system.
string sourceFilePath = @"C:\MyData\TestFile.txt";
string destinationFilePath = @"C:\temp\Data.txt";
bool overWrite = true;
File.Copy(sourceFilePath, destinationFilePath, overWrite);

Note: The overwrite parameter passed to the Copy method call indicates that the copy
process should overwrite an existing file if it exists at the destination path. If you pass
false to the Copy method call, and the file already exists then the Common Language
Runtime (CLR) will throw a System.IO.IOException.

The "Delete" method deletes an existing file from the file system.
string sourceFilePath = @"C:\MyData\TestFile.txt";

File.Delete(sourceFilePath);

The "Exists" method checks whether a file exists on the file system.
string sourceFilePath = @"C:\MyData\TestFile.txt";
bool doesFileExist = File.Exists(sourceFilePath);

The "GetCreationTime" method obtains the date time stamp that describes when
a file was created, from the metadata associated with the file.
string sourceFilePath = @"C:\MyData\TestFile.txt";
DateTime fileCreatedOn = File.GetCreationTime(sourceFilePath);

Using FileInfo class to manipulate files


Unlike the File class the FileInfo class provides instance members that you can use to
manipulate an existing file. Also in contrast to the File class that provides static methods
for direct manipulation, the FileInfo class works like an in memory representation of the
physical file.
Instantiating the FileInfo Class
string sourceFilePath = @"C:\MyData\TestFile.txt";
FileInfo fInfo = new FileInfo(sourceFilePath);

Once the instance of the FileInfo class is created, you can use the properties and
methods to interact with the file. The following list describes some of these properties
and methods.The "CopyTo" method enables the developers to copy an existing file to a
different directory on the file system.
string sourceFilePath = @"C:\MyData\TestFile.txt";
string destinationFilePath = @"C:\temp\Data.txt";
bool overwrite = true;
FileInfo fInfo = new FileInfo(sourceFilePath);
fInfo.CopyTo(destinationFilePath, overwrite);

Note: The overwrite parameter in the CopyTo method indicates that the copy process
should overwrite an existing file if it exists at the specified destination file path. If you
pass false to the CopyTo method, and the file already exists then the CLR will throw a
System.IO.IOException.

The "Delete" method enables the developers to delete a file.

string sourceFilePath = @"C:\MyData\TestFile.txt";


FileInfo fInfo = new FileInfo(sourceFilePath);
fInfo.Delete();

The "DirectoryName" property enables the developers to get the directory path to
the file.
string sourceFilePath = @"C:\MyData\TestFile.txt";
FileInfo fInfo = new FileInfo(sourceFilePath);
string directoryPath = fInfo.DirectoryName;
// returns C:\MyData

The "Exists" method enables the developers to determine if the specified file
exists within the file system.
string sourceFilePath = @"C:\MyData\TestFile.txt";
FileInfo fInfo = new FileInfo(sourceFilePath);
bool filesExists = fInfo.Exists;

The "Extension" property enables you to get the file extension of a file.
string sourceFilePath = @"C:\MyData\TestFile.txt";
FileInfo fInfo = new FileInfo(sourceFilePath);
bool filesExtn = fInfo.Extension;

The "Length" property enables the developers to get the length of the file in
bytes.
string sourceFilePath = @"C:\MyData\TestFile.txt";
FileInfo fInfo = new FileInfo(sourceFilePath);
long length = fInfo.Length;

DirectoryInfo and Directory class to Manipulating Directories


In an operating systems file system, the files are organized into directories. Hence, it is
very crucial for an application to interact and manipulate the file systems directory
structure. Interaction with directories may include checking that a directory exists before
writing a file or to remove directories after the process is complete as a cleanup policy.

The .NET Framework class library provides the Directory and DirectoryInfo classes for
such operations.
Using Directory class to manipulate directories
Similar to the File class, the "Directory" class provides static methods that enable you to
interact with directories, without instantiating a directory-related object in your code.

The "CreateDirectory" method creates a new directory on the file system.


string sourceDirPath = @"C:\MyData\Data";
Directory.CreateDirectory(sourceDirPath);

The "Delete" method deletes a directory at a specific path.


string sourceDirPath = @"C:\MyData\Data";
bool deleteRecursively = true;
Directory.Delete(sourceDirPath, deleteRecursively);

Note: The deleteRecursively parameter passed into the Delete method specifies
whether the delete process should delete any content that may exist in the
directory. If you pass false into the Delete method, and the directory is not empty
then the CLR will throw a System.IO.IOException.|

The "Exists" method determines if a directory exists on the file system.


string sourceDirPath = @"C:\MyData\Data";
bool tempDataDirectoryExists = Directory.Exists(sourceDirPath);

The "GetDirectories" method gets a list of all subdirectories within a specific


directory on the file system.
string sourceDirPath = @"C:\MyData\Data";
string[] subDirectories = Directory.GetDirectories(sourceDirPath);

The "GetFiles" method gets a list of all the files within a specific directory on the
file system.
string sourceDirPath = @"C:\MyData\Data";
string[] files = Directory.GetFiles(sourceDirPath);

The "DirectoryInfo" class provides instance members that enable you to access directory
metadata and manipulate the directory structure.
Using DirectoryInfo class to manipulate directories.
The "DirectoryInfo" class acts as an in-memory representation of a directory. Before you
can access the properties and execute the methods that the DirectoryInfo class
exposes, you must create an instance of the class.
Instantiating the DirectoryInfo Class
string sourceDirPath = @"C:\MyData\Data";
DirectoryInfo directory = new DirectoryInfo(sourceDirPath);

When you have created an instance of the DirectoryInfo class, you can then use its
properties and methods to interact with the directory. The following list describes some
of these properties and methods:

The "Create" method creates a new directory on the file system.


string sourceDirPath = @"C:\MyData\Data";
DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
directory.Create();

The "Delete" method deletes a directory at a specific path.


string sourceDirPath = @"C:\MyData\Data";
bool deleteRecursively = true;
DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
directory.Delete(deleteRecursively);

Note: The recursivelyDeleteSubContent parameter passed to the Delete method


call indicates whether the delete process should delete any content that may
exist in the directory. If you pass false to the Delete method call, and the directory
is not empty then the CLR will throw a System.IO.IOException.

The "Exists" property determines if a directory exists on the file system.


string sourceDirPath = @"C:\MyData\Data";
DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
bool directoryExists = directory.Exists

The "FullName" property gets the full path to the directory. The following example
shows how to get the full path to the tempData directory.
string sourceDirPath = @"C:\MyData\Data";
DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
string fullPath = directory.FullName;

The "GetDirectories" method gets a list of all subdirectories within a specific


directory on the file system. In contrast to the static File.GetDirectories method,
this instance method returns an array of type DirectoryInfo, that enables you to
use each of the instance properties for each subdirectory.
string sourceDirPath = @"C:\MyData\Data";
DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
DirectoryInfo[] subDirectories = directory.GetDirectories();

The "GetFiles" method gets a list of all the files within a specific directory on the
file system. In contrast to the static File.GetFiles method, this instance method
returns an array of type
FileInfo, that enables you to use each of the instance properties for each file.
string sourceDirPath = @"C:\MyData\Data";
DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
FileInfo[] subFiles = directory.GetFiles();

Depending on whether you require a simple one-line-of-code approach to manipulate a


directory, or something that offers slightly more flexibility, either the static Directory or
instance DirectoryInfo class should fulfill your requirements.

ANONYMOUS METHODS:

An anonymous method is a block of code that is used as the parameter for the
Delegate.Anonymous method allows coder to pass block of code rather than the name
of the method. Creating a anonymous method is a way to pass a code block as delegate
parameter.
Benefits:
1. To reduce code the amount of code

2. To reduce complexity of code.


3. To increase readability of code.
4. Anonymous method can use any local variable declared outside of method.
Rules
1. Cannot have jump statement that targets outside the anonymous method.
2. Jump statement from outside of anonymous method cannot target inside
anonymous method.
3. Anonymous method cannot use Ref and Out parameter from outside of
anonymous method.
Synatx:
Button1.Click+= delegate(Object o, EventArgs e)
{
MessageBox.Show("SCOTT");
}
Example:
using
using
using
using

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

namespace ConsoleApplication4
{
class Program
{
// Decelaring Delegate
public delegate void Display(String msg);
static void Main(string[] args)
{
// Delegate using anonymous method
Display del = delegate(string par)
Display del = delegate(string par)
{
Console.WriteLine("{0}", par);
};
// Invoking delegate
del("Christ");
Console.ReadLine();
}
}
}

In above code, Christ will get display as output. In above code, block of code is getting
passes as argument of delegate rather than name of the method.
Scope of the variable
The scope of variable of an anonymous method is the anonymous method block.
Anonymous method does not help speeding up the execution process because
for block of code, .Net generates the Anonymous name.