Sie sind auf Seite 1von 314

.

Net C# Data Types


Data is physically stored inside cells of memory. This memory could be physical
memory (Hard disk) or logical memory (RAM). Any cell of memory is represented
with a unique address. This address is more than some combination of numbers
or symbols.
C# language provides for practically all the data types. These types can be
divided in three categories: value types, reference types and pointer types.
There are some more basic concepts to be learnt before the discussion of the
data types. This is about variables and constants. A Variable is a named cell of
memory used for data storage. A Variable value can be changed anytime. Every
variable must have a type and this type must be set before it is used. Qualifying a
variable with a type is called as declaration of variable. The type of a variable is
the most important aspect and it defines the behavior of variable. All variables
can be divided into seven main categories depending on the context of usage:

1.
2.
3.
4.
5.
6.
7.

Static variables.
Variable of instance.
Array's elements.
Parameters given by reference.
Parameters given by value.
Returned values.
Local variables.

Static Variables will be alive throughout the life of a program. It can be declared
using static modifier.
An Instance variable is a variable declared without static modifier. Usually it is
declared inside a class or structure definition.
Parameter Values can be viewed as input parameters into methods:
public static void Sum(int a, int b)
{
Console.WriteLine("The sum of elements {0} and {1} is {2}",a,b,a + b);
}
This code writes in console values of variables a, b and their summary value.
Now if the values of these parameters are modified inside the method, this
change will not be reflected inside the main function. It is because the compiler
creates copies of them when it passes them as value types. This ensures that
their original values are not modified.

Instead if one wants to modify the parameter variables inside the function, C#
has something called Reference variables. Reference variables also have a
modifier out which can be used before their type. Look at the following example:
public static void SumRef(ref int a, ref int b)
{
a = 4;
b = 6;
Console.WriteLine("The sume of elements {0} and {1} is {2}",a,b,a + b);
}
Now this method modifies the value of variables a and b with values 4 and 6.
These values are retained even after the execution of the function gets
completed.
If the parameters need to be returned then they can be qualified with out modifier
or as returned parameter in method definition. Here is an example of both of
them, in which both of them return the same value:
public static int SumOut(int a, int b, out int sum1)
{
sum1 = a+b;
Console.WriteLine("The sum1 of elements {0} and {1} is {2}",a,b,a+b);
return sum1;
}
In main function it must be called in the next manner:
int sume ;
sume = SumeOut(2,2, out sume);
Constants in C#:
Constant type of data cannot be changed. To declare a constant the keyword
const is used. An example for the constant declaration is: const double PI =
3.1415;
Values types in C#:
Value type stores real data. When the data are queried by different function a
local copy of it these memory cells are created. It guarantees that changes made
to our data in one function don't change them in some other function. Let see at a
simple example:

public class IntClass


{
public int I = 1;
}
Here we have simple class that contains only one public data field of integer
type. Now have a look on its usage in main function:

static void Main(string[] args)


{
// test class
int i = 10;
int j = i;
j = 11;
IntClass ic1 = new IntClass();
IntClass ic2 = ic1;
ic2.I = 100;
Console.WriteLine("value of i is {0} and j is {1}",i,j);
Console.WriteLine();
Console.WriteLine("value of ic1.I is {0} and ic2.I is {1}",ic1.I,ic2.I);
Console.WriteLine();
}
Reference Types in C#:
In the above example, assume that First we have two value type i and j. Also
assume that the second variable is initialized with the value of the first one. It
creates new copy in memory and after it the values of these variables will be
next:
i = 10;
j = i;
There are a few more things written in the above example for explaining the
Reference Types in C#. At first, the variable ic1 of IntClass is created using
dynamic memory allocation. Then we initialize the variable ic2 with value of ic1.
This makes both the variables ic1 and ic2 referring to the same address. If we
change a value of ic2, it automatically changes the value of ic1.
Now, over to the discussions about the important value types used in C#. The
category simple types contains some predefined or system types that also are
commonly used in other programming languages. It contains integer types: byte,
Sbyte, Long, Ulong, Short, Ushort, int, Uint. These common types differs only
range of values and sign.

Next simple type is character type. To declare a variable of this type need use
keyword char. It can take values of characters or numbers as 16-digit symbol of
the type Unicode.
The Boolean type has only two values: true, false. But these values cannot be
assigned with a 0 or 1 as in C++ language.
Next category of simple types is floating point types. It contains two types float
and double. Float type can get values in range from 1.5*10-45 to 3.4*1038.
Double type has range of values from 5.0*10-324 to 1.7*10308.
A structural value types are struct and enum. Struct is a the same as class
but it uses real values not references. The following code snippet contains the
definition for struct:
struct Point3D
{
public float m_x;
public float m_y;
public float m_z;
public float [] GetArray()
{
float [] arr = new float[3];
arr[0] = m_x;
arr[1] = m_y;
arr[2] = m_z;
return arr;
}
}
The above is declaration for a simple structure of real 3D point. As you see a
class declaration looks very similar to the struct except that the class also has a
constructor.
Enumerated types can be used to create some set of identifiers that can have
values of simple type. Let us see at example of enum type:
public enum Days
{
Monday,

Tuesday,
Wensday,
Thursday,
Friday,
Saturday,
Sunday
}
In example there are enum that has days of week names. The values of days by
default are in range from 0 to 6.
Common types in C#:
Object in C# language is universal; it means that all supported types are
derived from it. It contains only a couple of methods: GetType() - returns a type of
object, ToString() returns string equivalent of type that called.
Next type is class. It is declared in the same manner as structure type but it has
more advanced features.
Interface is an abstract type. It is used only for declaring type with some abstract
members. It means members without implementations. Please, have a look at
piece of code with a declaration for a simple interface:
interface IRect
{
int Width
{
get;
set;
}
int Height
{
get;
set;
}
int CalculateArea();
}
The members of interface can be methods, properties and indexers.

Next reference type to be dealt is delegate. The main goal of delegate usage is
encapsulation of methods. It most like at pointers to function in C++.
String is common type that is used in almost all programming languages of
high level. An example of string declaration and initialization:
string s = "declaration and init";
The last very used reference type is array. Array it is set of elements that have
the same type. Array contains list of references on memory cells and it can
contain any amount of members. In C# there are three types of arrays: onedimensional, two-dimensional and jagged array.
So, this covers almost all types used in C#. All these types can be cast to
another type using special rules. An implicit casting can be done with types when
values of variables can be converted without losing of any data. There is special
type of implicit casting called boxing. This enables us to convert any type to the
reference type or to the object type. Boxing example:

// boxing
char ch = 'b';
object obj = ch;
Console.WriteLine("Char value is {0}",ch);
Console.WriteLine("Object value is {0}",obj);
Console.WriteLine();
This piece of code prints the same values of integer type variable and object
type variable. The opposite process to the boxing is un-boxing. An example for
un-boxing is as follows.

// unboxing
float q = 4.6f;
object ob = q;
Console.WriteLine("Object value is {0}",ob);
float r = (float)ob;
Console.WriteLine("Float value is {0}",r);
So, it is main item of common data type creating and using. All sources are
attached. To compile and run it need to run .NET command line. Just type: csc
DataTypes.cs. It creates DataTypes.exe that can be run as standard executable
file.

.Net C# Tutorial Intermediate


Language - MSIL
Microsoft Intermediate Language (MSIL) is a platform independent language
that gets compiled into platform dependent executable file or dynamic link library.
It means .NET compiler can generate code written using any supported
languages and finally convert it to the required machine code depending on the
target machine.
To get some clarity in this language we need to write some code. In this tutorial
we?ll use a very simple piece of source code in C# .Net. Now we need to
compile this code using csc command in Microsoft .NET on the command line.
To do this, please type next string: csc ILSample.cs. After it compiler will create
an executable file named ILSample.exe.
After this type the command called ILDasm. It will open application called
Intermediate Language Disassembler. In file menu choose open and find our
executable file.This application opens our assembly showing all structural units
viz., classes, methods, data fields and all global and local application data. Now if
you click on the method it shows code in intermediate language. This code is
most like at language with independent set of instructions.

public double GetVolume()


{
double volume = height*width*thickness;
if(volume<0)
return 0;
return volume;
}

You can get the strings of Microsoft Intermediate Language code using
ILDasm:

.method public hidebysig instance float64


GetVolume() cil managed
{
// Code size 51 (0x33)

.maxstack 2
.locals init ([0] float64 volume,
[1] float64 CS$00000003$00000000)
IL_0000: ldarg.0
IL_0001: ldfld float64 OOP.Aperture::height
IL_0006: ldarg.0
IL_0007: ldfld float64 OOP.Aperture::width
IL_000c: mul
IL_000d: ldarg.0
IL_000e: ldfld float64 OOP.Aperture::thickness
IL_0013: mul
IL_0014: stloc.0
IL_0015: ldloc.0
IL_0016: ldc.r8 0.0
IL_001f: bge.un.s IL_002d
IL_0021: ldc.r8 0.0
IL_002a: stloc.1
IL_002b: br.s IL_0031
IL_002d: ldloc.0
IL_002e: stloc.1
IL_002f: br.s IL_0031
IL_0031: ldloc.1
IL_0032: ret
} // end of method Aperture::GetVolume

To clearly understand that IL really is immediately language you should write


the same code in VB .NET and look at these two sources in IL. These methods
will be almost identical.
The main advantages of IL are:

1. IL isn?t dependent on any language and there is a possibility to create


applications with modules that were written using different .NET
compatible languages.
2. Platform independence - IL can be compiled to different platforms or
operating systems.

OOP & C#
The skeleton of object - oriented programming is of course the concepts of

class. This C# tutorial on OOPS explains classes and their importance in


implementation of object ? oriented principles.
Any language can be called object ? oriented if it has data and method that use
data encapsulated in items named objects. An object ? oriented programming
method has many advantages, some of them are flexibility and code reusability.
All the programming languages supporting Object oriented Programming will
be supporting these three main concepts:

1. Encapsulation
2. Inheritance
3. Polymorphism
Encapsulation in C#:
Encapsulation is process of keeping data and methods together inside objects.
In this way developer must define some methods of object?s interaction. In C# ,
encapsulation is realized through the classes. A Class can contain data
structures and methods. Consider the following class.

public class Aperture


{
public Aperture()
{
}
protected double height;
protected double width;
protected double thickness;
public double GetVolume()
{
double volume = height*width*thickness;
if(volume<0)
return 0;
return volume;
}
}

In this example we encapsulate some data such as height, width, thickness


and method GetVolume. Other methods or objects can interact with this object
through methods that have public access modifier. It must be done using ?.?
operator.
Inheritance in C#:
In a few words, Inheritance is the process of creation new classes from already
existing classes. The inheritance feature allows us to reuse some parts of code.
So, now we have some derived class that inherits base class?s members.
Consider the following code snippet:

public class Door : Aperture


{
public Door() : base()
{
}
public bool isOutside = true;
}

As you see to inherit one class from another, we need to write base class name
after ?:? symbol. Next thing that was done in code Door () ? constructor also
inherits base class constructor. And at last we add new private field. All members
of Aperture class are also in Door class. We can inherit all the members that has
access modifier higher than protected.
Polymorphism in C#:
Polymorphism is possibility to change behavior with objects depending of
object?s data type. In C# polymorphism realizes through the using of keyword
virtual and override. Let look on the example of code:

public virtual void Out()


{

Console.WriteLine("Aperture virtual method called");


}
//This method is defined in Aperture class.
public override void Out()
{
Console.WriteLine("Door virtual method called");
}

Now we need to re-define it in our derived Door class. The usage of virtual
methods can be clarified when we creating an instance of derived class from the
base class:
Aperture ap = new Door();
ap.Out();
In such cases, the runtime keeps record of all the virtual function details in a
table called VMT(Virtual Method Table) and then in runtime dynamically picks the
correct version of the function to be used. Here it uses Out() method from derived
class of course.

.Net C# Tutorial Namespaces


A Namespace in Microsoft .Net is like containers of objects. They may contain
unions, classes, structures, interfaces, enumerators and delegates. Main goal of
using namespace in .Net is for creating a hierarchical organization of program. In
this case a developer does not need to worry about the naming conflicts of
classes, functions, variables etc., inside a project.
In Microsoft .Net, every program is created with a default namespace. This
default namespace is called as global namespace. But the program itself can
declare any number of namespaces, each of them with a unique name. The
advantage is that every namespace can contain any number of classes,
functions, variables and also namespaces etc., whose names are unique only
inside the namespace. The members with the same name can be created in
some other namespace without any compiler complaints from Microsoft .Net.
To declare namespace C# .Net has a reserved keyword namespace. If a new
project is created in Visual Studio .NET it automatically adds some global
namespaces. These namespaces can be different in different projects. But each
of them should be placed under the base namespace System. The names space
must be added and used through the using operator, if used in a different project.

Please now have a look at the example of declaring some namespace:

using System;
namespace OutNamespace
{
namespace WorkNamespace
{ /// can be placed some classes, structures etc.
}
}

In this example we create two namespaces. These namespaces have


hierarchical structure. We have some outer one named OutNamespace and the
inner one called WorkNamespace. The inner namespace is declared with a
C# .Net class WorkItem.
The next logical discussion after a namespace is classes. A class is the basis
of object ? oriented programming. It encapsulates the data and methods into one
itself and manipulates them through the interaction with that object.

class WorkItem
{
public WorkItem()
{
}
static WorkItem()
{
m_counter = 1;
}
public static int GetCounter()
{
return m_counter;
}
private static int m_counter;
public virtual void Status()

{
}
internal bool IsWorking
{
get
{
return m_isWorking;
}
set
{
m_isWorking = value;
}
}
private bool m_isWorking = true;
}

The above sample contains the .Net namespace with the class WorkItem
inside it.
As already discussed, a class is the basis of Object oriented programming. A
class must have a constructor. The constructor method is used for initialization
purposes. Each class can have different modifiers which pertains to the type and
functionality of the class. Some such modifiers are: new, public, protected,
internal, private, abstract, and sealed. A class members can also have these
modifiers. In the above example, there is declared special constructor type ?
static constructor. It uses only for class not for its instances. In the same way we
can access to the static members of class.
OutNamespace.WorkNamespace.WorkItem item = new WorkItem();
int i = WorkItem.GetCounter();
In this piece of code there was created some instance of WorkItem but called
using its full name (including all namespace?s names). The second line it is an
access to the public static property of WorkItem. There are many advanced
features that can be used in class constructing process. One of them
polymorphism that can be realized though the virtual methods.
.Net Framework basics

When we speak about .Net, we mean by .NET framework. .NET Framework is


made up of the Common Language Runtime (CLR), the Base Class Library
(System Classes). This allows us to build our own services (Web Services or
Windows Services) and Web Applications (Web forms Or Asp .Net), and
Windows applications (Windows forms). We can see how this is all put together.?

Above Picture shows overall picture, demonstrating how the .NET languages
follows rules provided by the Common Language Specifications (CLS). These
languages can all be used?Independently to build application and can all be used
with built-in data describers (XML) and data assessors (ADO .NET and SQL).
Every component of the .NET Framework can take advantage of the large prebuilt library of classes called the Framework Class Library (FCL). Once
everything is put together, the code that is created is executed in the Common
Language Runtime. Common Language Runtime is designed to allow any .NETcompliant language to execute its code. At the time of writing, these languages
included VB .Net, C# and C++ .NET, but any language can become .NETcompliant, if they follow CLS rules. The following sections will address each of
the parts of the architecture.
.Net Common Language Specifications (CLS):
In an object-oriented environment, everything is considered as an object. (This
point is explained in this article and the more advanced features are explained in
other articles.) You create a template for an object (this is called the class file),
and this class file is used to create multiple objects.
TIP: Consider a Rectangle. You may want to create many Rectangle in your
lifetime; but each Rectangle will have certain characteristics and certain
functions. For example, each rectangle will have a specific width and color. So
now, suppose your friend also wants to create a Rectangle. Why reinvent the
Rectangle? You can create a common template and share it with others. They
create the Rectangle based on your template. This is the heart of object-oriented
programming?the template is the class file, and the Rectangle is the objects built

from that class. Once you have created an object, your object needs to
communicate with many other Objects.
Even if it is created in another .NET language doesn?t matter, because each
language follows the rules of the CLS. The CLS defines the necessary things as
common variable types (this is called the Common Type System CTS ), common
visibility like when and where can one see these variables, common method
specifications, and so on. It doesn?t have one rule which tells how C# composes
its objects and another rule tells how VB .Net does the same thing . To steal a
phrase, there is now ?One rule to bind them all.? One thing to note here is that
the CLS simply provides the bare rules. Languages can adhere to their own
specification. In this case, the actual compilers do not need to be as powerful as
those that support the full CLS.
The Common Language Runtime (CLR):
The heart of .net Framework is Common Language Runtime (CLR). All .NETcompliant languages run in a common, managed runtime execution environment.
With the CLR, you can rely on code that is accessed from different languages.
This is a huge benefit. One coder can write one module in C#, and another can
access and use it from VB .Net. Automatic object management, the .NET
languages take care of memory issues automatically. These are the few listed?
benefits which you get from CLR.
Microsoft Intermediate Language (MSIL):
So how can many different languages be brought together and executed
together??Microsoft Intermediate Language (MSIL) or, as it?s more commonly
known, Intermediate Language (IL). In its simplest terms, IL is a programming
language.?If you wanted to, you could write IL directly, compile it, and run it. But
why would want to write such low level code? Microsoft has provided with higherlevel languages, such as C#, that one can use. Before the code is executed, the
MSIL must be converted into platform-specific code. The CLR includes
something called a JIT compiler in which the compiler order is as follows.
Source Code => Compiler => Assembley =>Class Loader =>Jit Compiler
=>Manged Native Code=>Execution.
The above is the order of compilation and execution of programs. Once a
program is written in a .Net compliant language, the rest all is the responsibility of
the frame work.

Methods and properties

Any class in an object-oriented language has method and property members.


These are the places where the actual business logic or functionality is written
and executed. This tutorial explains how to create and use methods and
properties in C#.

C# Methods:
Method is object-oriented item of any language. All C# programs are constructed
from a number of classes and almost all the classes will contain methods. A class
when instantiated is called an object. Object-oriented concepts of programming
say that the data members of each object represent its state and methods
represent the object behavior.

Method Signature in C#:


Each method is declared as follows:
Return-type methodname ( Parameterslist );
For better understanding of methods let consider following example. We have a
class Man. It can have many fields like that:
public class Man
{
public Man(){}
private int m_old;
private string m_name;
public string WhatIsYourName()
{
Console.WriteLine(m_name);
return m_name;
}
public string HowOldAreYou()
{
Console.WriteLine(m_old.ToString());
return m_old;
}
}
The private members m_old and m_name define some state of objects that can
be created as instances of our class. Also the class Man has two methods, which
serve some of our requests. Method string WhatIsYourName() writes current
object?s name to the console and returns it, and the second one similar to first
return age of man and also writes an output to the console.

The return type in the example above returns strings, which is an in-built data
type. The methods can also return any generic C# type or any custom types
created by us.
Passing Parameters to Methods in C#:
The input parameters can be passed in two ways.
Value type
Reference type.
If parameters are passed as value types a new copy of it will be created and
passed inside the function. If they are created as reference types, only the
address of the parameters will be passed.
See next example:
public int CalculateBirthYear(int year)
{
int b = year - m_old;
Console.WriteLine("Birth year is {0}",b);
return b;
}
If input parameter pass as reference type it must use keyword ref, in that way
we operate with the same cell in memory. That?s mean it can be changed inside
any method. A small example for a parameter passed by reference is:
public int CalculateBirthYear(ref int year)
{
int b = year - m_old;
Console.WriteLine("Birth year is {0}",b);
return b;
}
Now, the function CalculateBirthYear can even modify the value of year as it is
passed by reference.

Output Parameters in Methods:


The return values in any function will be enough for any one if only one value is
needed. But in case a function is required to return more than one value, then
output parameters are the norm. This is not supported in C++ though it can be
achieved by using some programming tricks. In C# the output parameter is
declared with the keyword out before the data type. A typical example is as
follows.

public void CalculateBirthYear(ref int year, out int birthyear)


{
int b = year - m_old;
Console.WriteLine("Birth year is {0}",b);
birthyear = b;
return;
}
Strictly speaking there is no difference between ref and out parameters. The only
difference is that the ref input parameters need an input value and the out
parameters don?t.

Variable arguments in C#:


The C# language supports variable arguments through a keyword called
params. A typical example for the declaration of a function with variable argument
signature is as follows.
Public void functionName(int a, params int[] varParam);

Method Overloading in C#:


A method is considered to be an overloaded method, if it has two or more
signatures for the same method name. These methods will contain different
parameters but the same return types.
A simple example for an overloaded methods are:
Public void functionName(int a, params int[] varParam);
Public void functionName(int a);

Property in C#:
Property ? it is a special method that can return a current object?s state or set it.
Simple syntax of properties can see in the following example:
public int Old
{
get {return m_old;}
set {m_old = value;}
}
public string Name
{
get {return m_name;}
}

Here are two types of properties. A first one can set or get field of class named
m_old, and the second is read only. That?s mean it can only get current object?s
state.
The significance of these properties is its usability. These properties need not be
called with any function names like objectname.get or objectname.set etc., But
they can be directly assigned the values or retrieve the values.

C# .Net and Java


This article compares the same program written in the C# and Java languages
and then compares the dissembled code of both languages.
Java Hello Program:

class Hello
{
public static void main(String args[])
{
System.out.println("Hello");
}
}

Disassembled Java Hello Program:

class Hello
{
Hello()
{
// 0 0:aload_0
// 1 1:invokespecial #1 <Method void Object()>
// 2 4:return
}

public static void main(String args[])


{
System.out.println("Hello");
// 0 0:getstatic #2 <Field PrintStream System.out>
// 1 3:ldc1 #3 <String "Hello">
// 2 5:invokevirtual #4 <Method void PrintStream.println(String)>
// 3 8:return
}
}

Explanation of Java program:


To understand this you must have some knowledge of computer internals
concepts for eg. Opcodes, instruction templates etc. I assume that you already
know them.
As usual this code will also start with main method. The first line tells that
print ?Hello? it is a normal print statement. A specific instruction, with type
information, is built by replacing the ?T? in the instruction template in the opcode
column by the letter in the type column. In this case it is a load instruction for type
reference.
Invokespecial instruction must name an instance initialization method, a
method in the current class, or a method in a superclass of the current class.
Class and interface initialization methods are invoked implicitly by the Java
virtual machine; they are never invoked directly from any Java virtual machine
instruction, but are invoked only indirectly as part of the class initialization
process.
invokevirtual or invokespecial is used to access a protected method of a
superclass, then the type of the class instance being accessed must be the same
as or a subclass of the current class.
The Java virtual machine uses local variables to pass parameters on method
invocation. On class method invocation any parameters are passed in
consecutive local variables starting from local variable 0.
C# Hello Program:

using System;

class Hello
{
public static void Main(string[] args)
{
Console.WriteLine("Hello");
}
}

Disassembled C# Hello Program :

.method private hidebysig static void Main() cil managed


{
.entrypoint
// Code size 11 (0xb)
.maxstack 8
IL_0000: ldstr "Hello"
IL_0005: call void [mscorlib]System.Console::WriteLine(class System.String)
IL_000a: ret
} // end of method Hello::Main

Explanation of C# .Net Program:


The first line defines the Main method by using the .method MSIL keyword.
Note that the method is defined as being public and static, which are the default
modifiers for the Main method. Also note that this method is defined as
managed.
The next line of code uses the MSIL .entrypoint keyword to designate this
particular method as the entry point to the application. When the .NET runtime
executes this application, this is where control will be passed to the program.
Next, look at the MSIL opcodes on lines IL_0000 and IL_0005. The first uses
the the ldstr (Load String) opcode to load a hard-coded literal ("Hello") onto the
stack.
The next line of code calls the System.Console.WriteLine method. Notice that
the MSIL prefixes the method name with the name of the assembly that defines
the method. This line also tells us the number of arguments (and their types) that

are expected by the method. Here, the method will expect a System.String
object to be on the stack when it's called. Finally, line IL_000a is a simple ret
MSIL opcode to return from the method

C# .Net Tutorial Attributes


This article deals with the new C# .net features named attributes. This can be
used as a Self paced C# .net training or C# tutorial material.
C# .net Attributes provide a powerful method of associating declarative
information with C# code. It can work with types, methods, properties and other
language components.
As a thumb-rule, a class is said to be an attribute class, if it directly or indirectly
derives from the System.Attribute class.
Attributes in C# .net - Sample:
This C# tutorial on attributes uses custom attributes by defining an attribute
class. The class ProductInfo is derived from System.Attribute class. This class
contains information about application author and product version. The created
class is:

[AttributeUsage(AttributeTargets.All)]
public class ProductInfo : System.Attribute
{
public ProductInfo(double version,string name)
{
m_version = version;
m_authorName = name;
}
public double Version
{
get { return m_version; }
}

private double m_version = 1.00;


public string AuthorName
{
get { return m_authorName; }
}
private string m_authorName;
}

There is a new item in the first line of code. It is an attribute that allows us to use
a c# attribute keyword AttributeUsage to all elements of our class (parameter
AttributeTargets.All).
Now we can use these c# attributes in declaration of any other custom class:
[ProductInfo(1.005,"CoderSource"])
public class AnyClass { }
After creating simple custom type c# attributes, we can get information about
all its attributes at runtime. Such run-time information can be pulled out from a
class by using the namespace System.Reflection. In main function of our C#
tutorial program we can get from our object all information about custom
attributes. Next piece of code demonstrate it:

MemberInfo membInfo;
membInfo = typeof(AnyClass);
object [] attributes;
attributes = membInfo.GetCustomAttributes(typeof(ProductInfo),true);
if(attributes.GetLength(0)!=0)
{
ProductInfo pr = (ProductInfo) attributes[0];
Console.WriteLine("Product author: {0}",pr.AuthorName);
Console.WriteLine("Product version; {0}",pr.Version);
}

Using standard methods of getting type information and members of his type we
can get all custom attributes.
The example in this C# tutorial uses only one of three library c# attributes
(AttributeUsage). It uses only with declaration some custom c# attribute. There
is another standard attribute called Conditional. It calls method with that
attribute only in case when method application has some needed condition. Most
often it is used to define some preprocessor commands (?#?). And the last
reserved attribute is Obsolete. It helps us to mark some elements of program
that are old to use. These are basic things about attributes and their usage in
applications.

C# .Net Tutorial Exceptions


This article is a basic c# tutorial dealing with exceptions in c# .net.
Practically any program including c# .net can have some amount of errors.
They can be broadly classified as compile-time errors and runtime errors.
Compile-time errors are errors that can be found during compilation process of
source code. Most of them are syntax errors. Runtime errors happen when
program is running.
It is very difficult to find and debug the run-time errors. These errors also called
exceptions. Rules of good coding style say that program must be able to handle
any runtime error. Exception generates an exception call at runtime. Exceptions
in C# can be called using two methods:

1. Using the throw operator. It call the manage code anyway and process an
exception.
2. If using the operators goes awry, it can generate an exception.
Simple Exceptions - .Net C# Tutorial:
C# language uses many types of exceptions, which are defined in special
classes. All of them are inherited from base class named System.Exception.
There are classes that process many kinds of exceptions: out of memory
exception, stack overflow exception, null reference exception, index out of range
exception, invalid cast exception, arithmetic exception etc. This c# tutorial deals
with DivideByZero c# exception and custom classes in c# exceptions.
C# has defined some keywords for processing exceptions. The most important
are try, catch and finally.

The first one to be known is the try operator. This is used in a part of code,
where there exists a possibility of exception to be thrown. But operator ?try? is
always used with the operators: catch and finally.
See the following example of handling a simple exception in c#.

//Sample code for C# Exception tutorial using try , catch


// try catch exception
int zero = 0;
try
{
int div = 100/zero;
}
catch(DivideByZeroException)
{
Console.WriteLine("Division by zero exception passed");
}

This code in runtime throws a DivideByZeroException and writes some


message through the console. But if you want to release some resources that
were created you must use try ? finally construction. Finally will be called even if
there were no exceptions raised.

//Sample code for C# Exception tutorial using try, finally


Bitmap bit = null;
// try finally exception
try
{
bit = new Bitmap(100,100);
}
finally
{
bit.Dispose();
Console.WriteLine("bitmap is disposed");

In the similar way we can use try ? catch ? finally construction. The attached c#
tutorial program contains sample including all the three.
Custom Exception Classes - C# Tutorial:
Some larger projects might have a requirement of creating their own custom
exception classes. Let us try to create class that validates email address. It will
validate for the ?@? symbol. Please have a look on the following piece of code:

//Sample code for C# .Net Exception tutorial - validates an email address


public class TextException : Exception
{
public TextException() : base()<br>
{
}
public TextException(string message) : base(message)
{
}
}
public class MailValidator
{
MailValidator()
{
}
private static char symbol = '@';
public static void TestEnteredMail(string mailAddress)
{

if(mailAddress.IndexOf(symbol)==-1)
{
Console.WriteLine("The string entered is not a valid email address");<br>
throw(new TextException());
}
}
}

Here were created a C# .Net TextException class that inherits from


System.Exception class of .NET class library. Actually it does nothing, but there is
an additional class MailValidator. It has TestEnteredMail method that raises a
TextException. Now look at usage of it in Main function.

try
{
MailValidator.TestEnteredMail(Console.ReadLine());
}
catch(TextException)
{
Console.WriteLine("Exception was passed");
}

So, if user enters mail address without it throws an exception. All the sources
are attached and compliable. The example can be compiled using .NET
command line through the csc command line program. You only need to type
csc filename.cs.

C# .Net Tutorial Interfaces

This C# Tutorial deals with interfaces in C# .Net. An Interface is a reference


type and it contains only abstract members. Interface's members can be Events,
Methods, Properties and Indexers. But the interface contains only declaration
for its members. Any implementation must be placed in class that realizes them.
The interface can't contain constants, data fields, constructors, destructors and
static members. All the member declarations inside interface are implicitly public.
Defining an Interface:
Let us look at a simple example for c# interfaces. In this example interface
declares base functionality of node object.
interface INode
{
string Text
{
get;
set;
}
object Tag
{
get;
set;
}
int Height
{
get;
set;
}
int Width
{
get;
set;
}
float CalculateArea();
}
The above INode interface has declared a few abstract properties and function
which should be implemented by the derived classes.

//Sample for Deriving a class using a C# .Net interface - c# tutorial


public class Node : INode
{
public Node()
{}
public string Text
{
get
{
return m_text;
}
set
{
m_text = value;
}
}
private string m_text;
public object Tag
{
get
{
return m_tag;
}
set
{
m_tag = value;
}
}
private object m_tag = null;
public int Height
{
get
{
return m_height;

}
set
{
m_height = value;
}
}
private int m_height = 0;
public int Width
{
get
{
return m_width;
}
set
{
m_width = value;
}
}
private int m_width = 0;
public float CalculateArea()
{
if((m_width<0)||(m_height<0))
return 0;
return m_height*m_width;
}
}
Now the above code has created a c# class Node that inherits from INode c#
interface and implement all its members. A very important point to be
remembered about c# interfaces is, if some interface is inherited, the program
must implement all its declared members. Otherwise the c# compiler throws an
error.

The above code was a simple example of c# interface usage. Now this has to
be followed with some advanced details of interface building in C# .Net. The
previous example used only names of methods or properties that have the same
names as in interface. But there is another alternative method for writing the
implementation for the members in class. It uses full method or property name
e.g. INode.CalculateArea () {// implemetation}.
Multiple Inheritance using C# interfaces:
Next feature that obviously needs to be explained is multiple inheritance using
c# interfaces. This can be done using child class that inherits from any number of
c# interfaces. The inheritance can also happen with a combination of a C# .Net
class and c# interfaces. Now let us see a small piece of code that demonstrate
us multiple inheritance using only interfaces as parent data types.
class ClonableNode : INode,ICloneable
{
public object Clone()
{
return null;
}
// INode members
}
The above example created a class ClonableNode. It implements all the
functionality of INode interface in the same way as it was done in Node class.
Also it realizes Clone method only one item of IClonable interface of .NET library.
is Operator for C# .Net interfaces - C# Tutorial:
At last a new C# operator that can be used to define that class should be
explained. It is the is operator. Look at the following piece of code:

if(nodeC is INode)
Console.WriteLine("nodeC is object of INode type");
else
Console.WriteLine("nodeC isn't object of INode type");
In example nodeC object was created as ClonableNode type, but when we run
program "if operator" returns true. It means that nodeC also is of INode type.

C# .Net Tutorial Multithreading


Any Windows application must have one or more processes. A Process is
structural unit with a memory block and using some set of resources. For each
executable, the Windows operating system creates some isolated memory block.
This C# .Net Tutorial tries to explain the basics of Multithreading in C# .Net.
Every process must have at least one thread. The first thread is created with a
process and is known as primary thread. This Primary Thread is entry point of
application. In traditional Windows applications it is the method WinMain() and in
console applications it is named main().
Main goal of creating multithreading application is performance improvement.
As an example, imagine a situation where in a user starts a long process (e.g.
copying), he can?t use a single threaded application and wait for an infinite time
for the operation to get completed. But if he uses multi?threading application he
can set copying process in the background and interact with application without
any problems.
At first, if one wants to create a multi-threaded application an important point to
be remembered is, a global variable, which is being accessed by different
threads, can try to modify the same variable. This is a generic problem, which is
solved using a mechanism called Synchronization of threads. Synchronization is
nothing but the process of creating some set of rules to operate data or
resources.
The C# .Net language has a powerful namespace which can be used for
programming with Threads as well as Thread Synchronization in C# .Net
programming. The name of the namespace is Sytem.Threading. The most
important class inside this namespace for manipulating the threads is the C# .Net
class Thread. It can run other thread in our application process.
Sample program on C# Multithreading - C# Tutorial:
The example it creates an additional C# .Net class Launcher. It has only one
method, which output countdown in the console.

//Sample for C# tutorial on Multithreading using lock


public void Coundown()
{

lock(this)
{
for(int i=4;i>=0;i--)
{
Console.WriteLine("{0} seconds to start",i);
}
Console.WriteLine("GO!!!!!");
}
}

There is a new keyword lock inside the above chunk of .Net C# tutorial code.
This provides a mechanism for synchronizing the thread operation. It means at
the same point of time only one thread can access to this method of created
object. Unless the lock is released after completion of the code, the next routine
or iteration cannot enter the block.
To understand it more clearly please have a look at the piece of main method?s
code:

Launcher la = new Launcher();


Thread firstThread = new Thread(new ThreadStart(la.Coundown));
Thread secondThread =new Thread(new ThreadStart(la.Coundown));
Thread thirdThread = new Thread(new ThreadStart(la.Coundown));
firstThread.Start();
secondThread.Start();
thirdThread.Start();

As you see there were created three additional threads. These threads start a
method of object that has Launcher type. The above program is a very simple

example of using multi-threading in C#. Net. But C# .Net allows us to create


more powerful applications with any level of complexity.

C# .Net Tutorial Reflection


Reflection is the feature in .Net, which enables us to get some information
about object in runtime. That information contains data of the class. Also it can
get the names of the methods that are inside the class and constructors of that
object.
To write a C# .Net program which uses reflection, the program should use the
namespace System.Reflection. To get type of the object, the typeof operator
can be used. There is one more method GetType(). This also can be used for
retrieving the type information of a class. The Operator typeof allow us to get
class name of our object and GetType() method uses to get data about object?s
type. This C# tutorial on reflection explains this feature with a sample class.

public class TestDataType


{
public TestDataType()
{
counter = 1;
}
public TestDataType(int c)
{
counter = c;
}
private int counter;
public int Inc()
{
return counter++;
}
public int Dec()
{
return counter--;
}
}

At first we should get type of object that was created. The following C# .Net code
snippet shows how to do it.
TestDataType testObject = new TestDataType(15);
Type objectType = testObject.GetType();
Now objectType has all the required information about class TestDataType. We
can check if our class is abstract or if it is a class. The System.Type contains a
few properties to retrieve the type of the class: IsAbstract, IsClass. These
functions return a Boolean value if the object is abstract or of class type. Also
there are some methods that return information about constructors and methods
that belong to the current type (class). It can be done in a way as it was done in
next example:

Type objectType = testObject.GetType();


ConstructorInfo [] info = objectType.GetConstructors();
MethodInfo [] methods = objectType.GetMethods();
// get all the constructors
Console.WriteLine("Constructors:");
foreach( ConstructorInfo cf in info )
{
Console.WriteLine(cf);
}
Console.WriteLine();
// get all the methods
Console.WriteLine("Methods:");
foreach( MethodInfo mf in methods )
{
Console.WriteLine(mf);
}

Now, the above program returns a list of methods and constructors of


TestDataType class.

Reflection is a very powerful feature that any programming language would like
to provide, because it allows us to get some information about objects in runtime.
It can be used in the applications normally but this is provided for doing some
advanced programming. This might be for runtime code generation (It goes
through creating, compilation and execution of source code in runtime).
The Sample code can be downloaded from here. The attached example can be
compiled using .NET command line csc command. Type csc Reflection.cs. This
will create the executable Reflection.exe, which can be run as a normal
executable.

COM Interop
The ultimate goal of COM Interop is to provide access to the existing COM
components without requiring that the original component be modified. This
tries to make the .NET types equivalent to the COM Types.

COM Interop and Marshalling:


COM had a mechanism of marshalling and un-marshalling to convert
between the source and target data types. This is now totally covered in
COM Interop using RCW or Runtime Callable Wrapper. This automatically
converts the .Net data types to the corresponding COM data types.

RegAsm and tlbimp in COM Interop


In addition, COM Interop allows COM developers to access managed
objects as easily as they access other COM objects. It provides a specialized
utility (RegAsm.exe) that exports the managed types into a type library and
registers the managed component as a traditional COM component. At run
time, the common language runtime marshals data between COM objects and
managed objects as needed.
This tutorial shows how C# can use COM objects to develop applications.
First thing to be done is the creation of wrapper class for the selected COM
object. It can be done manually through the command line application called
TlbImp.exe (Type Library Importer). This utility converts COM type library
to the .NET Framework metadata. This procedure can be done automatically
through the .NET environment. We just need to add reference to the COM
object to our C# project. So, type in .NET command line next string: tlbimp

$WindowsPath$\system32\quartz.dll /out: quartzNET.dll. This command


will create a new dll with types that are compatible with any of Managed
.NET languages. Now we can add this dll to our C# project or compile our
C# file with additional feature "/r quartzNET.dll".
The following is an example of usage this COM object in C# managed code:
quartzNET.FilgraphManager manager = new
quartzNET.FilgraphManagerClass();
quartzNET.IMediaControl mc = (quartzNET.IMediaControl)manager;
mc.RenderFile(args[0]);
mc.Run();
// Wait for completion.
Console.WriteLine("Press Enter to continue.");
Console.ReadLine();
Here is the MediaControl object, which was created in COM. This
application gets a name of video file that we want to play from command
line and shows it. So, this is a simple example of usage COM Interop. To
compile an attached example we just need this quartzNET.dll (is attached
too) and .NET command line. Type here next command csc
InteropSample.cs /r:quartzNET.dll. It must create an executable file, but it
can be run using command line, just type InteroPsample.exe some.avi. So, it
opens a console application and also runs a standard Windows media player
control to play the video.
.Net C# Delegates and Events
This tutorial describes some basics about some of the great features of C#
language namely Delegates and Events. These new constructs are used in
object-oriented programming languages like C# and Java.
Delegates in C# .Net:
If we look at C++ there is a feature called callback function. This feature uses
Pointers to Functions to pass them as parameters to other functions. Delegate is
a similar feature but it is more type safe, which stands as a stark contrast with C+
+ function pointers. A delegate can hold reference/s to one more more functions
and invoke them as and when needed.
A delegate needs the method's name and its parameters (input and output
variables) when we create a delegate. But delegate is not a standalone
construction. it's a class. Any delegate is inherited from base delegate class of

.NET class library when it is declared. This can be from either of the two classes
from System.Delegate or System.MulticastDelegate.
If the delegate contains a return type of void, then it is automatically aliased to
the type of System.MulticastDelegate. This can support multiple functions with a
+= operator. If the delegate contains a non-void return type then it is aliased to
System.Delegate class and it cannot support multiple methods.
Let us have a look at the following sample code.
class Figure
{
public Figure(float a, float b, float c)
{
m_xPos = a;
m_yPos = b;
m_zPos = c;
}
public void InvertX()
{
m_xPos = - m_xPos;
}
public void InvertY()
{
m_yPos = - m_yPos;
}
public void InvertZ()
{
m_zPos = - m_zPos;
}
private float m_xPos = 0;
private float m_yPos = 0;
private float m_zPos = 0;
}
Now, we have a class named Figure and it has three private fields that use to
store position and three methods to invert this position by every axis. In main
class we declare delegate as follows:
public delegate void FigureDelegate();

And now in the main function we should use it like this:


Figure figure = new Figure(10,20,30);
FigureDelegate fx = new FigureDelegate(figure.InvertX);
FigureDelegate fy = new FigureDelegate(figure.InvertY);
FigureDelegate fz = new FigureDelegate(figure.InvertZ);
MulticastDelegate f_del = fx+fy+fz;
In this example we create three delegates of FigureDelegate type and attach to
these elements our three methods from Figure class. Now every delegate keeps
the address of the attached function. The last line of code is very interesting,
here we create a delegate of base type (MulticastDelegate) and attach three of
our already created delegates. As all our methods are of void return type they are
automatically of type MutlticastDelegate and a MulticastDelegate can support
multiple methods invocation also. Hence we can write
Figure figure = new Figure(10,20,30);
FigureDelegate fMulti = new FigureDelegate(figure.InvertX);
fMulti += new FigureDelegate(figure.InvertY);
fMulti();

Events in C# .Net:
Delegate usefulness does not just lie in the fact that it can hold the references
to functions but in the fact that it can define and use function names at runtime
and not at compile time. A large goal of design delegates is their applicability in
events model of .Net. Events are the actions of the system on user manipulations
(e.g. mouse clicks, key press, timer etc.) or any event triggered by the program.
To understand the usage of delegates for event model, the previous examples
are used here. We should add to our Figure class next things:
public delegate void FigureHandler(string msg);
public static event FigureHandler Inverted;
public void InvertZ()
{
m_zPos = - m_zPos;
Inverted("inverted by z-axis");
}
Now we have a delegate declared and event that uses this delegate's type. In
every function we should call our event. The next code snippet should explain it
clearly:

static void Main(string[] args)


{
Figure figure = new Figure(10,20,30);
Figure.Inverted+=new Test.Figure.FigureHandler(OnFigureInverted);
figure.InvertX();
figure.InvertZ();
}
private static void OnFigureInverted(string msg)
{
Console.WriteLine("Figure was {0}",msg);
}
So, in the main function we should create an object of figure class and attach
event handler to the method OnFigureInverted. And when we call any of invert
methods the event is fired and it calls our event handler. The application will print
the following string into the console: Figure was inverted by x-axis Figure was
inverted by z-axis There was simple examples of using delegates and events and
should be treated as a starting point to learn it more yourself. Download the C#
Delegates source files from the link. To compile and run it need to run .NET
command line. Just type: csc TestClass.cs. It creates TestClass.exe that can be
run as standard executable file.
C# Method Overloading
Last Update: 9 February, 2005
In complex applications written in C#, we may need many methods which do
essentially similar functions but are just different enough to be considered
unique. For example, we may have to calculate a person's tax liability and would
need to implement a method for doing this calculation in our application program.
However, there are many different rules when it comes to tax calculations and
they vary throughout the world. While there may be many rules, one basic
equation stays the same: Your net income equals your gross income minus a
computed tax amount. It is the method of computing your tax that varies.
We would probably have to implement different methods for each type of tax
calculation. And, we could give each method a unique name such as TaxCalc1,
TaxCalc2, TaxCalc3, etc. But wouldn't it be nice to just name the method
TaxCalc and pass different arguments to it based on the computation desired?
For instance, let's say you live in a region within your country where you are
taxed on your personal income, the value of your home, and any income you
generate by doing business. On sales you generate through business activity,
you must pay a gross receipts tax on all sales. If you own your home, you must

pay a property tax on the imputed value of it. Then lastly, you must pay a tax on
all income you generate through a job with another employer.
An Example: Tax Calculation
For this article, we will use a hypothetical example of computing various taxes on
a person's property, sales, and income. Let's summarize the logical flow through
pseudocode:
HV = Home_Value
HR = Home_Tax_Rate
GS = Gross_Sales
GR = Gross_Sales_Tax_Rate
PI = Personal Income
If YOU_OWN_YOUR_OWN_HOME and DO_NOT_OWN_A_BUSINESS
THEN
Tax = TaxCalc(HV,HR) ' Calculate tax on the home's value
ELSE
If YOU_DO_NOT_OWN_YOUR_OWN_HOME and OWN_A_BUSINESS
THEN
Tax = TaxCalc(GS,GR) ' Calculate tax on your gross receipts from sales
ELSE
If YOU_OWN_YOUR_OWN_HOME and OWN_A_BUSINESS THEN
Tax = TaxCalc(HV,HR,GS,GR) ' Calculate tax on both your home and
gross receipts
ENDIF
ENDIF
ENDIF
Tax = Tax + TaxCalc(PI) ' And everyone gets a tax calculation on personal
income
The pseudo code says that if you own your own home but do not have a
business, then you will calculate your tax based on the home's value and the tax
rate on a home. If you don't own a home but you own a business then you will
calculate your tax based on your gross sales and gross sales tax rate. Finally, if
you own a home and a business then you will call TaxCalc and pass all four
values. Everyone is run through the TaxCalc method for personal income tax. We
don't have to pass a rate for personal income tax calculation because everyone
is at a fixed rate which is embedded within the method.
Keep in mind that this example of tax calculation is all hypothetical. Tax codes
and calculations, as you know, are much more complex than what is described
here throughout the world. But for the sake of this example, we see that we have
a method named TaxCalc that is able to take one, two, or four arguments based

upon the type of tax we are calculating. Without method overloading, we would
have to create a unique method name for each type of calculation we would have
to do. We would probably name each TaxCalc1, TaxCalc2, and TaxCalc3
respectively.
How does C# know which method to call? It's easy. It knows which method to
invoke based on the number and type of arguments passed to it. This is also
referred to as the signature of the method. If C# sees you are calling TaxCalc
with four arguments, then it will call that method with four receiving arguments.
The same is true for the other two methods as well.
The Overloaded Methods
Each method is defined as follows in our overloading example:
// This method takes for arguments: two amounts and two rates
public static double TaxCalc(double pamt1, double prate1, double pamt2,
double prate2)
{
double taxamt;
Console.WriteLine("Using method with 4 arguments");
taxamt = (pamt1 * prate1) + (pamt2 * prate2);
return taxamt;
} // *** TaxCalc ***
// This method only takes two arguments: an amount and a rate
public static double TaxCalc(double pamt1, double prate1)
{
double taxamt;
Console.WriteLine("Using method with 2 arguments");
taxamt = pamt1 * prate1;
return taxamt;
} // *** TaxCalc ***
// This method only takes one argument: an amount
public static double TaxCalc(double pamt)
{
double taxrate = 0.15;
double taxamt = 0;
Console.WriteLine("Using method with 1 argument");
taxamt = pamt * taxrate;
return taxamt;
} // *** TaxCalc ***

The methods are all very similar however they are differ by the number of
arguments used in the tax calculation. If we have two tax rates and two amounts,
C# would pick the first method based on four arguments and invoke that. The
same holds true for the other two methods.
Caveat
It is important to remember that C# determines which method to call based upon
the method's signature. If you were to define two methods with the same name
and the same number and type of passed arguments, you would get a compiletime error in Visual Studio .NET of:
Class1.cs(53): Class 'MethodOverload.MainClass' already defines a
member called 'TaxCalc' with the same parameter types
However, you can have two methods with the same name and the same number
of arguments as long as the argument types differ. Let's say, for instance, that
you want to have another one-argument method named TaxCalc that takes a
string argument. If the string is the literal "TaxTable1", then it will return the tax
rate used in personal tax calculations:
// This method only takes one argument as well but it differs
// from the above in the argument type.
public static double TaxCalc(string whichtable)
{
double taxrate = 0;
Console.WriteLine("Calling the method with on string argument");
if (whichtable == "TaxTable1")
taxrate = 0.15;
return taxrate;
} // *** TaxCalc ***
The Example Program: MethodOverLoad.exe
This article has an example application available for download with the above
methods. It is a C#.NET console application and can be invoked from a Dos
command window by typing in methodoverload in the folder containing
methodoverload.exe. The main driver implements the pseudocode we defined
previously:
static void Main(string[] args)
{
bool ownshome = false;

bool ownsbusiness = false;


string inputs;
double hr = 0;
double hv = 0;
double gr = 0;
double gs = 0;
double pi = 0;
double totaltax = 0;
double pitaxrate = 0;
Console.WriteLine("Do you own a home? (y/n)");
inputs = Console.ReadLine();
if (inputs == "y")
{
ownshome = true;
Console.WriteLine("What is its value?");
inputs = Console.ReadLine();
hv = Convert.ToDouble(inputs);
Console.WriteLine("What is the home tax rate?");
inputs = Console.ReadLine();
hr = Convert.ToDouble(inputs);
}
Console.WriteLine("Do you own a business? (y/n)");
inputs = Console.ReadLine();
if (inputs == "y")
{
ownsbusiness = true;
Console.WriteLine("What was your total sales?");
inputs = Console.ReadLine();
gs = Convert.ToDouble(inputs);
Console.WriteLine("What is the gross sales tax rate?");
inputs = Console.ReadLine();
gr = Convert.ToDouble(inputs);
}
if (ownshome && !ownsbusiness)
totaltax = TaxCalc(hv, hr);
else
if (!ownshome && ownsbusiness)
totaltax = TaxCalc(gs, gr);
else
if (ownshome && ownsbusiness)
totaltax = TaxCalc(hv, hr, gs, gr);

Console.WriteLine("How much did you make last year?");


inputs = Console.ReadLine();
pi = Convert.ToDouble(inputs);
totaltax = totaltax + TaxCalc(pi);
Console.WriteLine("Your total tax is {0}", totaltax);
pitaxrate = TaxCalc("TaxTable1");
Console.WriteLine("Personal tax rate is {0}", pitaxrate);
} // *** Main ***

Conclusion
Method overloading is a powerful concept in C# in that it helps to simplify code
reusability and clarity. If our example method of TaxCalc was placed in a .dll file
somewhere, I would only have to remember that I have to call TaxCalc and only
fill in the appropriate arguments to pass. Without method overloading, I would
have to try and remember which specific uniquely-named method to call. This
would present a problem if you do not code everyday using a particular method
in that time would be spent getting familiar with the methods all over.

Reflection in C#
This article is aimed to explain reflection in .NET Framework.

Reflection is one of the features of .Net framework and has greater


importance during the development of large applications. In brief it is a
powerful way of collecting and manipulate information present in
application's assemblies and its metadata. Metadata contain all the Type
information used by the application. The ability to obtain information at
runtime also makes it even more advantageous. When reflection is used
along with system.type, it allows the developer to get the valuable
information about all the types and about the assemblies. We can even create
the instances and then invoke various types that are used across the
application.
What is Reflection?
Reflection is the ability to find out information about objects, the
application details (assemblies), its metadata at run-time.

This allows application to collect information about itself and also


manipulate on itself. It can be used effectively to find all the types in an
assembly and/or dynamically invoke methods in an assembly. This includes
information about the type, properties, methods and events of an object and
to invoke the methods of object Invoke method can be used too. With
reflection we can dynamically create an instance of a type, bind the type to an
existing object, or get the type from an existing object and invoke its
methods or access its fields and properties. If Attributes (C#) are used in
application, then with help of reflection we can access these attributes. It can
be even used to emit Intermediate Language code dynamically so that the
generated code can be executed directly.
How to use Reflection in our applications?
System.Reflection namespace contains all the Reflection related classes.
These classes are used to get information from any of the class under .NET
framework. The Type class is the root of all reflection operations. Type is an
abstract base class that acts as means to access metadata though the
reflection classes. Using Type object, any information related to methods,
implementation details and manipulating information can be obtained. The
types include the constructors, methods, fields, properties, and events of a
class, along with this the module and the assembly in which these
information are present can be accessed and manipulated easily.
As mentioned earlier, we can use reflection to dynamically create an
instance of any type, bind the type to an existing object, or get the type from
an existing object. Once this is done appropriate method can be invoked,
access the fields and properties. This can be done by specifying the Type of
object or by specifying both assembly and Type of the object that needs to be
created. By this the new object created acts like any other object and
associated methods, fields and properties can be easily accessed. With
reflection we can also find out about various methods associated with newly
created object and how to use these object. To find out the attributes and
methods associated with an object we can use the abstract class MemberInfo,
this class is available under the namespace System.Reflection.

Understanding Constructors in C#
Constructors are used for initializing the members of a class whenever an
object is created with the default values for initialization.

If a class is not defined with the constructor then the CLR (Common
Language Runtime) will provide an implicit constructor which is called as
Default Constructor.
A class can have any number of constructors provided they vary with the
number of arguments that are passed, which is they should have different
signatures.

Constructors do not return a value.


Constructors can be overloaded.
If a class is defined with static and Non-static constructors then the
privilege will be given to the Non-static constructors.

The following are the access modifiers for constructors,


Public : A constructor that is defined as public will be called whenever a
class is instantiated.
Protected : A constructor is defined as protected in such cases where the
base class will initialize on its own whenever derived types of it are created.
Private : A constructor is defined as private in such cases whenever a class
which contains only static members has to be accessed will avoid the
creation of the object for the class.
Internal : An internal constructor can be used to limit concrete
implementations of the abstract class to the assembly defining the class. A
class containing an internal constructor cannot be instantiated outside of the
assembly.
External : When a constructor is declared using an extern modifier, the
constructor is said to be an external constructor.

Types of Constructors
i) Static : Used for initializing only the static members of the class. These
will be invoked for the very first time the class is being loaded on the
memory. They cannot accept any arguments. Static Constructors cannot have
any access modifiers.

Syntax ---Static ClassName()


{
//Initialization statements;
}
ii) Non-Static : are used for initializing the Non-Static and Static members
of a class. These will be invoked everytime a new object is defined for a
class.
Syntax --Public ClassName([argsInfo])
{
//Initialization statements;
}
Example :
Using System;
Class SampleConstructor
{
public static int s;
public int ns;
static SampleConstructor()
{
s = 10;
//ns = 20; --- Error cannot be assigned like this
}

public SampleConstructor()
{
ns=100;
s=200;
}
}
Class UseSampleConstructor
{
public static void Main()
{
SampleConstructor sc = new SampleConstructor();
Console.WriteLine({0},{1},sc.s, SampleConstructor.s, sc.ns);
}l
}l
Error(Cannot call like this)
If you observe in the above example the static variable `ns' cannot be
assigned a value in the static Constructor as it is a Non-static member of the
class and a static constructor cannot initialize a Non-Static member.
Also as you see in the above code the Non-static constructor initializing the
values for both the static and Non-Static members of class, when we say `sc'
we are creating an object for the class and using the object we do the call the
methods, it is not valid to call a static member of class using the object of
the class we have to call it through the method name/Constructor name
through the member will be invoked.
Methods help you to separate code into modules that perform a given task.
Every program or application have a starting entry point to there application
that decide the path execution and all. We already come across different
application where the starting point or entry point is main ( ) method.

Methods provide the flexibility where we can separate the code into
modules. This will make easy understanding of code, more reusability and
increase performance. The method can pass parameters to another method
and return the value that is optional. If the method contains void keyword,
this means method will not return any thing.

Syntax:

access specifier return-type methodname (parameter list) {


//Statement
}

Method Chaining:- The method chaining is the process by which one


method calls another method. The caller method can pass parameters to the
called method and in return the called method return some value (this is
optional).

Example

The following example will demonstrate the method concepts along with the
method chaining.

using System;

using System.Collections.Generic;
using System.Windows.Forms;

namespace cSHARPEXAMPLES
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[ STAThread ]
static void Main ()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault( false );
Application.Run( new Form1 ());
}
}
}

Method Chaining: Here we can add two values to the form and User can
select the options i.e. 1 Add, 2 Subtract, 3 Multiply and 4 Divide. And result
will be displayed when the user click Execute.

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

namespace cSHARPEXAMPLES

{
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
}
private void Form4_Load( object sender, EventArgs e)
{
lblEnter.Text = "" ;
lblEnter.Text = lblEnter.Text + "Enter 1 to Add" + "\n" ;
lblEnter.Text = lblEnter.Text + "Enter 2 to Sub" + "\n" ;
lblEnter.Text = lblEnter.Text + "Enter 3 to Multiply" + "\n" ;
lblEnter.Text = lblEnter.Text + "Enter 4 to Divide" + "\n" ;
}
private void btnExecute_Click( object sender, EventArgs e)
{
int _valDec = Int32 .Parse(txtdecision.Text);
int _firstVal = Int32 .Parse(textBox1.Text);
int _secondVal = Int32 .Parse(textBox2.Text);

switch (_valDec)
{
case 1: fxadd(_firstVal, _secondVal); break ;
case 2: fxsubtract(_firstVal, _secondVal); break ;
case 3: fxmultiply(_firstVal, _secondVal); break ;
case 4: fxdivide(_firstVal, _secondVal); break ;
default :
MessageBox .Show( "Please Enter Specified Value.." );
break ;
}
}

void fxadd( int firstarg, int secondarg) {


int _add = firstarg + secondarg;
txtResult.Text = _add.ToString();
}
void fxsubtract( int firstarg, int secondarg) {
int _sub = (firstarg - secondarg);
txtResult.Text = _sub.ToString();
}

void fxmultiply( int firstarg, int secondarg){


int _mul = firstarg * secondarg;
txtResult.Text = _mul.ToString();
}
void fxdivide( int firstarg, int secondarg){
int _div = firstarg / secondarg;
txtResult.Text = _div.ToString();
}
}
}

Output

Namespaces are C# program elements that are used for logical grouping of
the classes. They also provide assistance in avoiding name clashes between
two sets of codes. Namespaces doesn't corresponds to file or directory
names. The using directives e.g.
Using System;
This contains number of classes, by including this namespace we can access
those classes that are there in the System namespace.

Example:- Demonstrate Namespace

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Test = rootnamespace.firstlevelnamespace;

namespace cSHARPEXAMPLES
{
public partial class Form5 : Form

{
public Form5()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{
rootnamespace.firstlevelnamespace. TestDemo .fxTest();
rootnamespace.firstlevelnamespace. TestDemo11 .fxDisplay();
Test. TestDemo11 .fxDisplay();
}
private void button2_Click( object sender, EventArgs e)
{
secondnamespace.firstlevelnamespace. TestDemo1 .fxTest1();
secondnamespace.firstlevelnamespace. TestDemo1 .fxTest();
}
}
}

namespace rootnamespace

{
// nested namespace
namespace firstlevelnamespace
{
class TestDemo
{
public static void fxTest()
{
MessageBox .Show( "Fire UP rootnamespace " );
}
}
class TestDemo11
{
public static void fxDisplay()
{
MessageBox .Show( "Display under rootnamespace " );
}
}
}
}

namespace secondnamespace
{
// nested namespace
namespace firstlevelnamespace
{
class TestDemo1
{
public static void fxTest1()
{
MessageBox .Show( "Fire UP secondnamespace" );
}
public static void fxTest()
{
MessageBox .Show( "Fire UP
secondnamespace.firstlevelnamespace.fxTest" );
}
}
}
}

Example Explanation:

In above example we have 3 namespaces i.e. cSHARPEXAMPLES,


rootnamespace, secondnamespace.Rootnamespace contains
irstlevelnamespace namespace,2 classes i.e TestDemo, TestDemo11 and
these classes contains methods i.e. fxTest(),fxDisplay(). Secondnamespace
contains nested namespace i.e. firstlevelnamespace, 1 class i.e. TestDemo1
and the class contains methods i.e fxTest1(),fxTest().
Classes are the core of OOP's. Classes are declared by using the keyword
classes. Classes contain data members that represent the class. We can create
object of the class, objects are entities and we can create as many number of
objects of a given class.

Syntax:
Class classname {
//Variable declaration
// Method declaration
}

Classes can contain the following entities inside its declaration:

Constructors

Destructors

Fields

Methods

Properties

Indexers

Delegates

Events

Nested Classes.

Constructors:- Constructors are called or initialized automatically whenever


an object of the class is created. The purpose of the constructors is to
initialize the class members whenever an object of the class is created.

Constructor name is same as of class name.

Constructor doesn't return any value, nor even void

Constructor initialize the class members at the time of its creation

There are different types of constructor:

Default Constructor

Parameterized Constructor

Copy Constructor

Destructor:- Destructor is used to deallocate any memory that is allocated to


the object at the time of its creation. Destructor is used for memory
management and avoids any memory leaks that occur in the case of
reference variables that store on heap memory.
Destructor keeps tracks of all the unwanted and unused memory and frees it
when we are not using it.

In .net the memory management is automatically done through GC i.e.


garbage collection, this is responsible for deallocation of memory.

The reference variable memory allocated on heap and here the job of
GC comes into picture, it will deallocate the memory that is not in
used.

The value type variables allocated memory on stack, here the variable
doesn't require any GC, they just fall from the stack if there are not in
used.

Example: Demonstrate Constructor, Destructor and used of Static


method .

TestDemo.cs

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

namespace cSHARPEXAMPLES
{
public class TestDemo

{
String str;
static String str2 = "default" ;
public TestDemo() {
//Constructor
str = "Hi" ;
}
public TestDemo( String strdefault) {
//Parameterized Constructor
str = strdefault;
}
public String display(){
return str;
}
public static String staticfx() {
return str2 + " This comes from Static fx" ;
}
~TestDemo() {
// Clean Up Code Here.
}

}
}

Form6.cs

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

namespace cSHARPEXAMPLES
{
public partial class Form6 : Form
{
public Form6()
{
InitializeComponent();

}
private void button1_Click( object sender, EventArgs e)
{ //Calling Default Constructor
TestDemo obj = new TestDemo ();
MessageBox .Show( "default Constructor :: " + obj.display());
}
private void button2_Click( object sender, EventArgs e)
{ //Calling Parameterized Constructor
TestDemo obj1 = new TestDemo ( "Vikrant" );
MessageBox .Show( "Parameterized Constructor :: " + obj1.display());
}
private void button3_Click( object sender, EventArgs e)
{ //Calling Static method of the class
MessageBox .Show( "Static method :: " + TestDemo .staticfx());
}
}
}

Output:

Click on: Default Constructor Button

Click on: Parameterized Constructor Button

Click on: Static method Button

Inheritance is one of the primary concepts of object-oriented programming.


Inheritance is the process by which we can inherits the properties or methods
of one class into the other class. The concept behind inheritance, take the
base class that contains methods and properties and inherits it into the
derived class, that now contains all the members and properties of the base
class as well as its own newly added members or properties. The following
are the advantages of Inheritance:-

Reuse the existence code

Save time, we need not do the code verification and testing.

Here, we can add and modify the methods of the existing class.

Help in modularization of code.

Types of Inheritance:

The following are the types of inheritance exist in C# programming.

Single Inheritance:
Here we have single base class that is inherited by the derived class. Here
the derived class has all the features of the base class and can add new
features or modify existing features. The inheritance also depends on the
access specifier that is used at the time of base class inheritance.

Multi-level Inheritance:

In the multi-level inheritance, here we having a chain of inheritance i.e. the


base class A is inherited by derived class B, and it is further inherited by
another derived class C. So, the feature we have in base class A, is also there
in Derived class B, and all the combination features of class A and class B
are there in derived class C.

Multiple Inheritance:
In C#, we don't have multiple inheritance where one class can inherit two
base classes. So, the multiple inheritance can be done by using the concept
of interfaces. Here one class can inherit one class and can implements more
than one interface.

Hybrid Inheritance:
The hybrid inheritance can also be done through with the help of interface.
Here the derived class cans implements more than two interfaces and only
one class.

Example: Demonstrate Inheritance

DerivedClass7.cs

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

namespace cSHARPEXAMPLES
{
public class parentClass7
{
String str = "Parent:::" ;
public parentClass7() {
str = "Parent Constructor" ;

}
public String display() {
return str;
}
public String Show() {
return "Base Show" ;
}
}
public class DerivedClass7 : parentClass7
{
String testStr = "Derived::" ;
public DerivedClass7() {
testStr = "Derived Constructor" ;
}
public String display1() {
return testStr;
}
public String Show1()
{
return base.Show();

}
}
}

Form7.cs

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

namespace cSHARPEXAMPLES
{
public partial class Form7 : Form
{
public Form7()
{

InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{
DerivedClass7 obj = new DerivedClass7 ();
MessageBox.Show( "Call to Parent Method :: " + obj.display());
MessageBox.Show( "Call to Derived Method :: " + obj.display1());
}
private void button2_Click( object sender, EventArgs e)
{
DerivedClass7 obj = new DerivedClass7 ();
MessageBox.Show( "Call in Derived method that further call Base
method ===>" +
obj.Show1());
}
}
}

OutPut:

When User Clicks On :Simple Inheritance Button

When User Clicks On :Calling Base Method in Derived Method Button

Polymorphism is the core concept of OOP's. Polymorphism means one name


many forms.

Types of polymorphism
1. Compile Time Polymorphism

2. Run Time Polymorphism

Compile Time Polymorphism


The compile time polymorphism, here the polymorphism is implemented
during compile time, that means at the time of compilation the compiler
knows where to bind the method. The compile time polymorphism can be
implemented through:

Method Overloading

Operator Overloading

Method Overloading:
In complex applications written in C#, we may need many methods which
do essentially similar functions but are just different enough to be considered
unique. So, we can define method overloading as if two or three method in a
class has same name but they differ by number of arguments or type of
argument.

Operator Overloading:
This provides a meaningful understanding of the operation by using operator
overloading. Here what we did is we overload an operator and change its
meaning, so that a valuable information is send to the programmer and this
help in reducing the complexity.

E.g.
If we need to add two matrix of 3X3
Matrix result = Matrix.Add(mat1, mat2); // this doesn't give any relevant
information

Run Time Polymorphism


The run time polymorphism, here the compiler doesn't know which method
to call at runtime. Here we can call the derived method through base class
pointer at runtime. The run time polymorphism can be implemented through:
Virtual Override Keyword.

Vitual function:
The virtual function is used to implement runtime polymorphism; here we
have same name method in the base class as well as in the derived class. We
can access the derived method using the base pointer. The virtual keyword
should be write in front of the base class method and in the derived class we
have to write override in front of the method. For Example:-

Class BaseClass {
Virtual void display () {//statements}
}
Class DerivedClass {
Override void display () {//statements}
}

Example: Demonstrate Polymorphism

BaseClass8.cs

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

namespace cSHARPEXAMPLES

{
class BaseClass8
{
String str = "Base" ;
public BaseClass8() { }
public String display() {
return str + ": BaseClass Display" ;
}
public virtual String show() {
return str + ": BaseClass Show" ;
}
}
}
DerivedClass8.cs

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

namespace cSHARPEXAMPLES

{
class DerivedClass8 : BaseClass8
{
String str = "Derived" ;
public DerivedClass8() { }
public new String display() { //NEW KEYWORD is USE TO HIDE THE
//SAME METHOD IN TH BASE CLASS
return str + ": Display Derived" ;
}
public override String show() { //OVERRIDE KEYWORD IS USED IF
//THE METHOD IN THE BASE CLASS IS VIRTUAL
return str + ": SHOW Derived:" ;
}
}
}

Form8.cs

using System;

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

namespace cSHARPEXAMPLES
{
public partial class Form8 : Form
{
public Form8()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{ //Virtual: Polymorphism at RunTime
BaseClass8 objBase = new DerivedClass8 ();
label5.Text = objBase.display();
label6.Text = objBase.show();

}
private void button2_Click( object sender, EventArgs e)
{
BaseClass8 objBase = new BaseClass8 ();
label1.Text = objBase.display();
label2.Text = objBase.show();
}
private void button3_Click( object sender, EventArgs e)
{
DerivedClass8 objDer = new DerivedClass8 ();
label3.Text = objDer.display();
label4.Text = objDer.show();
}
}
}

Output

Properties are used to protect the field in a class by reading and writing it
through the property. Here the field consists of one getter and one setter that
are associated with a given field. We can access this field through this
getter/setter combination.

Two ways to declare property in the class

1. One way to declare:


class PropertyDemo {

private String name; //Declare a field

public String getName() { //Getter

return name;

public void setName( String Value) {//Setter

name = value;

2.
Another way to declare:

class PropertyDemo {

private String name; //Declare a field

public String Name{

get{ return name;} //Getter

set{ name = value;} // Setter

Read-Only property:
We can declare a property as read-only; by only have its getter. So that the
user can't set the value of the field, because there is no setter for the field.
Hence we restrict the user to change the value of the field at any given time.

Write-Only property:

We can declare a property as write-only, by only have its setter. Here the
user can't access the value that is there in the field. We can manipulate the
value of the field by using its setter, but we can't get the value of this field.

Example: Demonstarte propery, Read-Only Property, Write Only Property.

ClsProperty9.cs

using System;
usingusing System.Collections.Generic;
using System.Text;

namespace cSHARPEXAMPLES
{
class ClsProperty9
{
private int age;
private String name;
private String lastName = "Dogra" ;
private String address;
public int getAge() {
return age;
}
public void setAge( int Value) {
age = Value;
}
public String getName()
{
return name;
}
public void setName( String Value)
{

name = Value;
}
//Read-Only property:Only Getter
public String getLastName()
{
return lastName;
}
//Write-Only Property: Only Setter
public void setAddress( String Value)
{
address = Value;
}
public String displayAddress()
{
return address;
}
}
}

Form9.cs

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

namespace cSHARPEXAMPLES
{
public partial class Form9 : Form
{
ClsProperty9 obj = new ClsProperty9 ();
public Form9()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{ //Setters Calls

obj.setAge( Int16 .Parse(textBox1.Text));


obj.setName(textBox2.Text);
obj.setAddress( " Chandigarh " ); //Write Only Property
}
private void button2_Click( object sender, EventArgs e)
{ //Getters Calls
MessageBox .Show( "Name: " + obj.getName());
MessageBox .Show( "Age: " + obj.getAge());
MessageBox .Show( "Last Name: " + obj.getLastName()); //Read
//Only property
MessageBox .Show( "Address: " + obj.displayAddress());
}
}
}

Output:

Click On: Set the Value


This will set the values in the class fields i.e. name, address

Click On: Get the Value


This will display the values that are set by the setters.

First value that we get is the name.

Second is the age value.

This field only has getter associated to it.

This field only has setter associated with it, we can


If properties are 'virtual fields', indexers are more like 'virtual arrays' .
They allow a class to emulate an array, where the elements of this array are
actually dynamically generated by function calls. They allow a class to be
used just like an array. On the inside of a class, you manage a collection of
values any way you want. These objects could be a finite set of class
members, another array, or some complex data structure. The following are
the advantages of the Indexers.

Regardless of the internal implementation of the class, its data can be


obtained consistently through the use of indexers.

Indexers aren't differentiated by name, and a class cannot declare two


indexers with the same signature. However, this does not entail that a
class is limited to just one indexer. Different indexers can have
different types and numbers of indexing elements (these being
equivalent to method parameters, except that each indexer must have
at least one indexing element, and the 'ref' and 'out' modifiers cannot
be used).

Example: Demonstrate Indexers

ClsIndexers10.cs

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

namespace cSHARPEXAMPLES
{
class ClsIndexers10
{
private String [] arrString;
private int arrSize;

public ClsIndexers10( int sizeofArray) { //Constructor


arrSize = sizeofArray;
arrString = new String [arrSize];
for ( int i=0;i<arrSize;i++){
arrString[i] = "No Value" ;
}
}

public string this [ int indexValue]


{
get {
return arrString[indexValue];
}
set {
arrString[indexValue] = value ;
}
}
public string [] this [ string data]
{
get {

for ( int i = 0; i < arrSize; i++)


{
if (arrString[i] == data)
{
arrString[i] = "Hi" ;
}
}
return arrString;
}
set
{
for ( int i = 0; i < arrSize; i++)
{
if (arrString[i] == data)
{
arrString[i] = "Hi" ;
}
}
}
}

}
}

Form10.cs

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

namespace cSHARPEXAMPLES
{
public partial class Form10 : Form
{
static int arrSize = 10;
ClsIndexers10 obj = new ClsIndexers10 (arrSize);
public Form10()

{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{ //Indexers Implementation : Using Integer
label1.Text = "" ;
obj[2] = "HHHI" ;
obj[5] = "Vikrant" ;
obj[9] = "Amit" ;
for ( int i = 0; i < arrSize; i++)
{
label1.Text = label1.Text + "Indexer at " + i + obj[i] + "\n" ;
}
}
private void button2_Click( object sender, EventArgs e)
{ //Indexers Implementation : Using String
label1.Text = "" ;
String [] arrString = obj[ "No Value" ];
for ( int i = 0; i < arrString.Length; i++)
{

label1.Text = label1.Text + "Indexer at " + i + obj[i] + "\n" ;


}
}
}
}

Output:

Click On: Indexer Implementation

Click On: Indexer With String

Structs is value-type user defined data type same as int, float, bool etc.
Structs features:

structs are value-type

In structs memory allocation can be done on stack.

No garbage collector required to remove structs variable because as


they are value type, the memory allocated is on stack and so no
memory allocated on heap, when structs variable are not in used they
just fall from the stack.

Structs can't have destructors.

Structs can't inherit another class or structs. This means there is no


concept of inheritance in structs.

Structs may inherit multiple interfaces. Interface is a reference type


and any class or structs that implements interface must override all the
methods that are there in the interface.

Example: Demonstrate Structs

ClsStruct11.cs

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

namespace cSHARPEXAMPLES
{
interface ITest
{
string Test();
}

struct Rectangle : ITest


{
public int length;
public int breath;
public int height;
public Rectangle( int length, int breath, int height)
{
this .length = length;
this .breath = breath;

this .height = height;


}
public Rectangle Add( Rectangle rect)
{
Rectangle newRect;
newRect.length = length + rect.length;
newRect.breath = breath + rect.breath;
newRect.height = height + rect.height;
return newRect;
}
public string Test()
{
return "Implements Interface in structs" ;
}
}

class ClsStruct11
{
public String display()
{

Rectangle rect1 = new Rectangle (10, 20, 30);


Rectangle rect2 = new Rectangle (110, 120, 130);
Rectangle rect3;
rect3 = rect1.Add(rect2);
return "Length :: " + rect3.length + "\n Breadth :: " + rect3.breath + "\n
Height :: " + rect3.height;
}

public string print()


{
Rectangle rect1 = new Rectangle (10, 20, 30);
return rect1.Test();
}
}
}

Form11.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;

using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace cSHARPEXAMPLES
{
public partial class Form11 : Form
{
public Form11()
{
InitializeComponent();
}

private void button1_Click( object sender, EventArgs e)


{ // Structs Implementation
label1.Text = "" ;
ClsStruct11 obj = new ClsStruct11 ();
label1.Text = obj.display();
}

private void button2_Click( object sender, EventArgs e)


{ // Structs Implementing Interface
label2.Text = "" ;
ClsStruct11 obj = new ClsStruct11 ();
label2.Text = obj.print();
}
}
}

Output:

Clicking On Both the Buttons: The concept behind the structs will be
executed and displayed.

An interface looks like a class, but has no implementation. An interface is a


C# reference type with members that do not have implementations.
Interfaces only have method signatures. The following are the properties of
the interfaces:-

It contains definitions of events , indexers , methods and/or properties


.

The reason interfaces only provide definitions is because they are


inherited by classes and structs , which must provide an
implementation for each interface member defined.

Interfaces are like protocol or standard that needs to be maintained by


the classes or structs that are implementing that interface.

We can have final variables and abstract methods in interface. This


means the classes or structs that are implementing interfaces need to
provide the body for all the methods that are there in interfaces.

No need to provide the access specifier for method that is there in


interface, all the methods are public.

We have the concept of inheritance in interface. One interface can


extends another interface.

Syntax:
Interface InterfaceName {
// method signature
}

Class implementing the Interfaces.

Class clsTest: ITestInterface


{
// method defined here
}

Structs Implementing Interface.


struct strTest: IstructsInterface
{
// method defined here
}

Interfaces may inherit other interfaces.

Example: Demonstrate Interfaces

ClsInterface12.cs

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

namespace cSHARPEXAMPLES
{
interface IParentInterace
{
String display();
}
interface IChildInterface : IParentInterace
{
String Show();
}
class ClsInterface12 : IChildInterface
{
String str = "Hi" ;
public ClsInterface12( String pStr) {
str = pStr;
}
public String Test() {
return str;
}

public String display()


{
return str + " : Display Of Base Interface" ;
}
public String Show()
{
return str + " : Show Of Child Interface" ;
}
}
}

Form12.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;

using System.Windows.Forms;

namespace cSHARPEXAMPLES
{
public partial class Form12 : Form
{
public Form12()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{
ClsInterface12 obj = new ClsInterface12 ( "Hello" );
label1.Text = obj.Test();
label2.Text = obj.display();
label3.Text = obj.Show();
}
private void Form12_Load( object sender, EventArgs e)
{
label1.Text = "" ;

label2.Text = "" ;
label3.Text = "" ;
}
}
}

Output:

Click On: Interface Executed Button

A delegate in C# language allows us to reference a method. The other way to


say this delegate is a function pointer. The function pointer is same as we
have pointer to an address now in this case we have pointer to a method
address. There are two types of delegates :-

Single-Cast Delegate:- Here the delegate will refer to or point to


single method or we can Say that the pointer is to single method from
the delegate.

Multi-Cast Delegate:-In the multi-cast delegate, the delegate refer to


or point to more than One method at runtime.

Delegates features:

Delegate is a function pointer.

Delegate declaration is same as method declaration, except they have


delegate modifier in front of it.

The method that a delegate refers or pointing to must have same


signature as of delegate method.

To use a delegate, we have to create the instance of the delegate and


pass the method that it is pointing too or referring to.

Invoke (), This method can be used to invoke the delegate.

The delegates can be declared by adding a delegate keyword in front of any


method. For Example- delegate void Mydelegate();

Note:- This is declaration of the delegate and it specifies the method


signature that it is pointing or referring. This means the signature of the

method that a delegate pointing has no parameter and will not return any
thing. But this is an example and we can say the delegate can refer to any
type of method.

Example: Demonstrate Delegates

ClsDelegate13.cs

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

namespace cSHARPEXAMPLES
{

class ClsDelegate13
{
delegate void Mydelegate ();
static String str = "" ;
static String sd = "" ;
public String singlecastfx()
{
sd = "" ;
sd = "Single Cast Delegate ==> " ;
Mydelegate d = null ;
d += new Mydelegate (singlecastdelegatefx);
d.Invoke();
sd = sd + " :: appender" ;
return sd;
}
public String multicastfx() {
str = "" ;
str = "starting Value ==> " ;
Mydelegate d = null ;
d += new Mydelegate (firstfx);

d += new Mydelegate (secondfx);


d();
str = str + " :: appender" ;
return str;
}
public void firstfx()
{
str = str + " :: firstfx" ;
}
public void secondfx()
{
str = str + " :: secondfx" ;
}
public void singlecastdelegatefx()
{
sd = sd + " ::singlecastdelegatefx" ;
}
}
}

Form13.cs

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

namespace cSHARPEXAMPLES
{
public partial class Form13 : Form
{
public Form13()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{ //Multi-cast delegate

ClsDelegate13 objDelegate = new ClsDelegate13 ();


MessageBox .Show(objDelegate.multicastfx());
}

private void button2_Click( object sender, EventArgs e)


{ //Single-cast delegate
ClsDelegate13 objDelegate = new ClsDelegate13 ();
MessageBox .Show(objDelegate.singlecastfx());
}
}
}

Output:

Clicking On: Single-cast Delegate Button

Clicking On: Mutil-cast Delegate Button

Exceptions are unforeseen errors that happen in your programs.


Programmers always detect and most of the time writes correct code to
avoid all the errors or exceptions that can distract the execution of the code
and cause unwanted results.

However, there are times when you don't know if an error will occur. For
example, you can't predict when you'll receive a file I/O error, run out of
system memory, or encounter a database error. These things are generally
unlikely, but they could still happen and you want to be able to deal with
them when they do occur. This is where exception handling comes in. When
exceptions occur, they are said to be "thrown". What is actually thrown is an
object that is derived from the S ystem. Exception class

Try/catch and Finally Block:

This is a way we can handle exceptions in C#.

Try Block:- In this block, we include all the suspected code. This
means the code that is most likely to cause exception.

Catch Block:- In this block we include all handlers that will be take
care of exception that occurs. We can have number of catch blocks
associated to single try block.

Finally Block : The finally block contains the cleanup code that we
needed whether the code is succeed or not. Most of the time we write
a code that will deal locate the memory that we associated in the
beginning like memory allocated to connection object.

Example: Exception Handling

Form14.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace cSHARPEXAMPLES
{
public partial class Form14 : Form
{
public Form14()
{
InitializeComponent();
}

private void button1_Click( object sender, EventArgs e)


{ //Simple Try/Catch Block
int dividebyZero = 0;
int a = 20;
int b = 0;
try
{
dividebyZero = (a / b);
}catch ( DivideByZeroException ex)
{
MessageBox .Show( "2nd EXCEPTION :: " + ex.ToString());
}catch ( Exception ex) {
MessageBox .Show( "EXCEPTION :: " +ex.ToString());
}
}

private void button2_Click( object sender, EventArgs e)


{ //Try,Catch and Finally Block
FileStream outputStream = null ;

FileStream inputStream = null ;


try {
outputStream = File.OpenWrite( "DestinationFile.txt" );
inputStream = File.OpenRead( "BogusInputFile.txt" );
}catch ( Exception ex) {
MessageBox .Show(ex.ToString());
}finally {
if (outputStream != null ) {
outputStream.Close();
MessageBox .Show( "OutputStream Closed." );
}
if (inputStream != null ) {
inputStream.Close();
MessageBox .Show( "InputStream Closed." );
}
}
}
}
}

Output:

Click On: Simple Try/catch Block Button

Click On: Try/catch and Finally Block Button

Attributes are elements that allow you to add declarative information to your
programs. This declarative information is used for various purposes during
runtime and can be used at design time by application development tools.
Attributes are also used extensively in securing .NET assemblies, forcing
calling code to be evaluated against pre-defined security constraints.
Attribute declared using the [and ]' brackets before any type declaration.

The following are the advantages the attributes provide:

Declarative information to your program

This information can be used at runtime or at compile time by


programmers.

DllImportAttribute: This attribute provide information to


communicate with the Win32 libraries.

ObsoleteAttribute: This provides compile time information to the


developer that this method is now deprecated.

Attribute add what is called metadata to your program.

Attributes are classes that can be written in C# and used to decorate


your code with declarative information.

Many attributes have parameter lists that allow inclusion of additional


information that customizes a program even further.

Examples of Attributes:-

[ Obsolete ]
public String firstDeprecatedFX(){}
[ ObsoleteAttribute ]
public String secondDeprecatedFX(){}
Obsolete ( "Don't Use This Method." )]
public String thirdDeprecatedFX()
[ STAThread ]
static void Main () {}

Note:- This attribute declare that this is the entry point for the application.
This indicates that C# program should communicate with unmanaged COM
code using the single threading apartment. The parameter provide
additional information about the attribute

Example To Demonstrate Attributes

The following is the screen appeared when run the form 15 program in the
source.

ClsAttribute15.cs

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

namespace cSHARPEXAMPLES
{
class ClsAttribute15
{
[ Obsolete ]
public String firstDeprecatedFX()
{

return "Call firstDeprecatedFX" ;


}

[ ObsoleteAttribute ]
public String secondDeprecatedFX()
{
return "Call secondDeprecatedFX" ;
}

[ Obsolete ( "Don't Use This Method." )]


public String thirdDeprecatedFX()
{
return "Call thirdDeprecatedFX" ;
}

}
}

Form15.cs

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

namespace cSHARPEXAMPLES
{
public partial class Form15 : Form
{
public Form15()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{ //Attribute : use to create method deprecated
ClsAttribute15 obj = new ClsAttribute15 ();

obj.firstDeprecatedFX();
//Deprecated Methods
obj.secondDeprecatedFX();
MessageBox .Show(obj.thirdDeprecatedFX());
}
}
}

Output:

Clicking On: Attribute fire up Button

An enumeration is a special kind of value type limited to a restricted and


unchangeable set of numerical values. Enums are strongly typed constants.
They are essentially unique types that allow you to assign symbolic names to
integral values.

Advantages of Enums:-

In the C# tradition, they are strongly typed, meaning that 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.

By default, these numerical values are integers, but they can also be
longs, Bytes, etc.

When you define an enumeration you provide literals which are then
used as Constants for their corresponding values.

Values specified in enumeration are static.

These values are final and you can't change the value at runtime.

The System.Enum BCL type is the base class of enum types and
contains methods that allow you to work with enums in different
ways, such as working with a list of names or values, converting from
value to name, and converting from name to value.

Syntax
enum enumname { //values}
Example:enum DayOfWeek {
Monday=2,

Tuesday,
Wednesday,
Thursday=10,
Friday,
Saturday,
Sunday
}
Note:-

The first literal, is unassigned then it value is set to 0.

For any other literal, if the value is unassigned then the value set is
greater than the value of the preceding literal.

By this the value of Monday is set to 0 and the value of Sunday is 6.

We can also specify the value to the literal in the enums.

Note:- Here the value will be Monday-2, Tuesday-3, Wednesday-4 and


Thursday-10, Friday-11, Saturday-12, Sunday-13.

Example: Demonstrate Enums

ClsEnum16.cs

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

namespace cSHARPEXAMPLES
{
enum DayOfWeek {
Monday,
Tuesday,

Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
enum ValuesEnum : byte
{
One = 1,
two,
three=5,
four,
five
}

class ClsEnum16
{
public String GetvalueEnteredByUser( int enteredValue) {
//user entered value
ValuesEnum valuesEnum = ( ValuesEnum )enteredValue;

String str = "" ;


switch (valuesEnum)
{
case ValuesEnum .One: str = "FIRST" ;
break ;
case ValuesEnum .two: str = "SECOND" ;
break ;
case ValuesEnum .three: str = "THIRD" ;
break ;
case ValuesEnum .four: str = "FOURTH" ;
break ;
case ValuesEnum .five: str = "FIFTH" ;
break ;
default : str = "default" ; break ;
}
return str;
}

public String CreateAndUseEnumType(){


DayOfWeek dayofWeek = DayOfWeek .Thursday;

//DayOfWeek dayofWeek = (DayOfWeek)4;


String strDay = "" ;
switch (dayofWeek)
{
case DayOfWeek .Monday: strDay = "Monday" ;
break ;
case DayOfWeek .Tuesday: strDay = "Tuesday" ;
break ;
case DayOfWeek .Wednesday: strDay = "Wednesday" ;
break ;
case DayOfWeek .Thursday: strDay = "Thursday" ;
break ;
case DayOfWeek .Friday: strDay = "Friday" ;
break ;
case DayOfWeek .Saturday: strDay = "Saturday" ;
break ;
case DayOfWeek .Sunday: strDay = "Sunday" ;
break ;
}
return strDay;

}
}
}
Form16.cs

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

namespace cSHARPEXAMPLES
{
public partial class Form16 : Form
{
public Form16()
{
InitializeComponent();

}
private void button1_Click( object sender, EventArgs e)
{ //Create and use Enums
ClsEnum16 obj = new ClsEnum16 ();
MessageBox .Show(obj.CreateAndUseEnumType());
}

private void button2_Click( object sender, EventArgs e)


{ //Enter Enum Value From User

int _userEnterValue = Int32 .Parse(textBox1.Text);


ClsEnum16 obj = new ClsEnum16 ();
MessageBox .Show(obj.GetvalueEnteredByUser(_userEnterValue));
}
}
}

Output
Click On: Enter Enum value from user Button

Click On: Create and Use Enums Type

Encapsulation is the process of wrapping up of data and members in a class.


Encapsulation provides the way to hide data from the external usage. This is
important in the scenario when we don't want our precious data to be used or
manipulated by external user. Encapsulation is an object-oriented principle
of hiding the internal state and behavior of an object, making your code
more maintainable.

Advantages of Encapsulation

Data-hiding through the access specifier private.

Reduce coupling between objects.

Increases the maintainability of code.

Wrapping up of data variables and members inside the class.

The following table will give the description of the Access modifiers
available in C#.

Access Modifier

Description (who can access)

Private

Private members can be accessed within the class


where they are declared. We can't access private
members outside the class, not even with the object of
the class.
This basically provides the concept of Data-Hiding.

Protected

Protected members scope can be outside the class but


only limited to the immediate derived class that is
inheriting the base class where the protected members
resides.
The protected can be used by the members of same
class or the members of derived class.

Internal

Here the internal members are accessible within the


same assembly.
If you don't specify any modifier, by default it is of
internal type.

Protected Internal

Here either accessed in the same assembly or the


derived assembly also. This is basically a combination
of protected and internal access modifiers.

Public

Public members can be accessed anywhere. No


restriction associated with this access modifier.

Sealed Class
The sealed keyword provides the restriction that no other class in the context
can inherit this class. By this, we can make our class not to be inherited by
other class. If the class tries to inherit the class that is declared as sealed, the
compile time error occurs.

1] Class declared as sealed


sealed class ClsSealed17 {// Any members }

Abstract Class
The class declared with abstract keyword, this means the class is only
provide the essential elements and not including the background details.
Abstraction is the process of including the essential elements and hiding the
details. In layman terms, we can say that a computer is the abstract form,
because we are not aware of the internal technicality.
If the class is declared as abstract, we have to give the body to all the
methods that are declared as abstract.

1] Class declared as abstract

abstract class clsAbstractDemo{


// This can contains abstract or concrete methods.
}

2] Abstract Members
public abstract string displayname();
Note:- The abstract methods can only include the signature of the method.

Example: Demonstrate Encapsulation

ClsEncapsulation17.cs

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

namespace cSHARPEXAMPLES
{
class Customer
{
public void CustomerRecord()
{
AddNewRecord();
UpdateExistingRecord();
DeleteRecord();
}
protected virtual string AddNewRecord()
{ return "Base: AddNewRecord" ; } //ADD NEW RECORD

protected virtual string UpdateExistingRecord()


{ return "Base: UpdateExistingRecord" ; } //UPDATE EXISTING
RECORD
protected virtual string DeleteRecord()
{ return "Base: DeleteRecord" ; } //DELETE EXISTING RECORD
}
class ClsEncapsulation17 : Customer
{
private string name = "" ; //Can't Access Outside the Class
private string address = "" ; //Can't Access Outside the Class
private string pri_Display() //Can't Access Outside the Class
{
return "This method can't be access outside the class" ;
}

public string CustomerName { //Public Property


get { return name; }
set { name = value ; }
}
public string CustomerAddress //Public property
{

get { return address; }


set { address = value ; }
}
public string CombineDisplay() //Public Method
{
return CustomerName + " :::" + CustomerAddress;
}
protected override string AddNewRecord() //Protected Method
{
return "protected method :: AddNewRecord" ;
}
protected override string UpdateExistingRecord() //Protected Method
{
return "protected method :: UpdateExistingRecord" ;
}
protected override string DeleteRecord() //Protected Method
{
base .DeleteRecord();
return "protected method :: DeleteRecord" ;
}

public string combineString()


{
string cmbStr = "" ;
cmbStr = cmbStr + AddNewRecord() + "\n" ;
cmbStr = cmbStr + UpdateExistingRecord() + "\n" ;
cmbStr = cmbStr + DeleteRecord();
return cmbStr;
}
}
}

ClsSealed17.cs

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

namespace cSHARPEXAMPLES
{
sealed class ClsSealed17

{
private string name = "" ;
public string CustomerName
{
get { return name; }
set { name = value ; }
}
public string displayName()
{
return name;
}
}
//Can't inherited a Sealed Class
class derivedClass //: ClsSealed17
{
}
}

ClsAbstract17.cs

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

namespace cSHARPEXAMPLES
{
abstract class clsAbstractDemo
{
private int _number = 10;
public string _name = "" ;

public abstract string displayname(); // Abstract method


public int calcTotal() //Concreate Method
{
return (_number * 10);
}
}
class ClsAbstract17 : clsAbstractDemo
{

public override string displayname() { //Abstract Method


return "Abstract Method Provide Body in Derived Class" ;
}
}
}

Output

Click On: Private Members Button

Click On: Public Members Button

Click On: Protected Members Button

Click On: Sealed

Click On: Abstract

A method's parameters are the types that get passed to it when the method is
called. The list of parameters begins by specifying zero or more 'fixed
parameters', and it may finish by specifying a single parameter-array. This
latter element - declared using the 'params' keyword - means that it is
possible to pass an arbitrary number of types to a single method.

Syntax: [Modifier] parameter-type parameter-identifier

[Modifier]: This is optional and can be either 'ref' or 'out'.

Parameter-type: This declares the type of the parameter.

Parameter-identifier: The name of the parameter.

There are 3 type of parameter that are passed to the method

Passing by Value

Passing by Reference

Output' Parameter.

Passing By Value:
The parameter modifiers 'ref' and 'out' relate to how the parameter is passed
into the method. Where neither of these modifiers is used, the parameter is
passed in 'by value'. By default we are passing variable by value. Here the
new copy of the variable is send to the called method. So changes done to
the variables are not reflected on the actual parameter.

Syntax:
passValueByValueType(_initialValue); //Call a method
private void passValueByValueType( int iV)
{ iV = 20; }

Passing By Reference:
In C# we can pass variables into methods 'by reference'. Where a variable is
passed by reference, the 'ref' modifier must be used both in the method head
and the method invocation (illustrated by the next code block). The changes
made to the formal argument will reflect on the actual argument.

Syntax:
passValueByReferenceType( ref _initialValue); //Calling Method
private void passValueByReferenceType( ref int iV)
{ iV = 20; }

Output' parameter:
Where a method parameter is defined (and invoked) using the 'out' modifier,
it is passed by reference. The difference between the 'out' and the 'ref'
modifier is this: a parameter modified by the 'out' keyword need not be
assigned a value before being passed into the method, but must be assigned a
value in the method.

Syntax:
passValueByOutParameter( out _initialValue, out _bValue);//Calling

Params' Modifier
One can pass an arbitrary number of types to a method by declaring a
parameter array with the 'params' modifier.

Syntax:
public int getTheTotalUsingParam( params int [] intArr)

Example: Demonstrate Parameter Passing in C#

Form18.cs:

using System;

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

namespace cSHARPEXAMPLES
{
public partial class Form18 : Form
{
public Form18()
{
InitializeComponent();
}
private void btnValue_Click( object sender, EventArgs e)
{ //Value
int _initialValue = Int16 .Parse(textBox1.Text);
MessageBox .Show( "Before Calling " +
_initialValue.ToString());

passValueByValueType(_initialValue);
textBox1.Text = _initialValue.ToString();
MessageBox .Show( "After Calling " +
_initialValue.ToString());
}
private void btnReference_Click( object sender, EventArgs e)
{ //Reference
int _initialValue = Int16 .Parse(textBox2.Text);
MessageBox .Show( "Before Calling " +
_initialValue.ToString());
passValueByReferenceType( ref _initialValue);
textBox2.Text = _initialValue.ToString();
MessageBox .Show( "After Calling " +
_initialValue.ToString());
}

private void btnOut_Click( object sende

r, EventArgs e)

{ //Out
bool _bValue;
int _initialValue = Int16 .Parse(textBox3.Text);

MessageBox .Show( "Before Passing " +


_initialValue.ToString());
passValueByOutParameter( out _initialValue, out _bValue);
textBox3.Text = _initialValue.ToString();
MessageBox .Show( "After getting the value " +
_initialValue.ToString());
}
private void passValueByReferenceType( ref int iV)
{
iV = 20;
}
private void passValueByValueType( int iV)
{
iV = 20;
}
private void passValueByOutParameter( out int iV, out bool bValue)
{
bValue = false ;
iV = 2;
if (iV > 40)

bValue = true ;
else
bValue = false ;
iV = iV * 20;
}
}
}

OutPut:

Clicking On:- Passing Parameter By Value

Clicking On:- Passing Parameter By Reference

Clicking On:- Passing Parameter By Out

C# is a language. The classes defined in the class libraries are used to


communicate with the database and we are using C# language to interact
with the database. In Ado.Net components we have number of classes that
are responsible to communicate with the database.

Introducing ADO.NET

Ado.Net is an Object-oriented set of libraries that allows you to interact with


data sources. Following are the data providers in ado.net.
1. System.Data.SqlClient:- contains classes that communicate with Ms
SQLServer.
2. System.Data.OracleClient:- communicate with Oracle.
3. System.Data.Oledb:- communicate to a data source that has an
OLEDB provider.
4. System.Data.Odbc:- communicate to a data source that has an ODBC
provider

ADO.NET OBJECTS
Ado.net includes many objects you can use to work with data. Some of the
primary objects are as follows:1. SqlConnection:- To interact with a database, you must have a
connection to it. The connection objects helps identifying the database
server, database name, user name and password. The connection
object is used by command objects.
2. SqlCommand:- You can use this object to send SQL statements to the
database. This can represent a SQL Statement or stored procedure.
3. SqlDataReader:- The data reader object allows you to obtain the
results of a Select statement from a command object. The data
returned from a data reader is a fast forward-only stream of data. This
fetch data in a sequential manner.

4. DataSet:- You can imagine dataset as a database. This contain


multiple datatable objects, which further contains columns and rows
objects. We can also define relationship among tables in the dataset.
This is disconnected approach.
5. SqlDataAdapter:- The SqlDataAdapter is used to fill dataset object
when reading the data and writes in a single batch when persisting
changes back to the database. A data adapter contains a reference to
the connection object and opens and closes the connection
automatically when reading from or writing to the data base. The data
adapter contains 4 command objects i.e. SELECT, UPDATE,
DELETE, and INSERT

Example: Demonstrate Database Interaction

This example will provide the interaction with the database. The user will
enter his credentials, if the user is valid and the credentials matched with the
database, he is able to view all the other users' credentials that are valid.

Form20.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;

using System.Windows.Forms;
using System.Data.SqlClient;

namespace cSHARPEXAMPLES
{
public partial class Form20 : Form
{
public Form20()
{
InitializeComponent();
}
private void btnLogin_Click( object sender, EventArgs e)
{ //Login
try
{
SqlConnection con = null ;
string conStr = "" ;
int _ExistFlag = 0;
conStr = "Data Source=localhost;initial
catalog=TestDB;uid=sa;pwd=sa" ;

con = new SqlConnection (conStr);


_ExistFlag = fnUserExists(con,txtName.Text,txtPassword.Text);
if (_ExistFlag == 0)
{ //Not A Valid User
MessageBox .Show( "Not A Valid User" );
}
else
{ // If Valid user Than Display all the Valid User that are there in
the DataBase
MessageBox .Show( "Valid User :: Display All the Valid User" );
fillgridWithValidUser(con);
}
}
catch ( Exception ex)
{
MessageBox .Show( "Exception Occurs.........." +ex.Message);
}
finally
{
txtName.Text = "" ;
txtPassword.Text = "" ;

}
}

/*
* Function: Whether a Valid User or Not
* Depending on the creadentials enter by user
*/
private int fnUserExists( SqlConnection con, string strUserName, string
strPassword)
{
SqlCommand cmd = null ;
int _ExistFlag = 0;
cmd = new SqlCommand ( "select count(*) from tblLogin where
UserName=@UserName and password=@Password " , con);
cmd.Parameters.Add( "@UserName" , SqlDbType.NVarChar).Value =
strUserName;
cmd.Parameters.Add( "@Password" , SqlDbType.NVarChar).Value =
strPassword;
cmd.CommandType = CommandType .Text;
con.Open();
_ExistFlag = Int16 .Parse(cmd.ExecuteScalar().ToString());
con.Close();

return _ExistFlag;
}

/*
* if the Credentials Enter By user is Valid:
* Then Display List Of all The Other Valid Users.
*/
private void fillgridWithValidUser( SqlConnection con)
{
SqlDataAdapter ada = null ;
DataSet dst = null ;
ada = new SqlDataAdapter ( "select * from tblLogin" , con);
dst = new DataSet ();
ada.Fill(dst, "Login" );
dataGridView1.DataSource = dst.Tables[0].DefaultView;
}
}
}

Output:

On Click: Login Button

There are varieties of operators available for use in C#. The C# language
defines the behavior of these operators when used in an expression with the
C# built-in data types. C# gives user the flexibility to change the default
behaviour of the operators that means, user can define the behavior of many
of the standard operators with his own structures and classes.

Suppose, for example, that you're writing a class that manages a set of
records read from a database. If another piece of code has two objects of
your class, it may want to write an expression that joins the records together
into a third object. This sounds like an addition operation, and it seems
natural for other pieces of code to write code like the following:
Records Records1;
Records Records2;
Records Records3;
Records3 = Records1 + Records2;

Your Records class would include a method that specifies "how objects of
the class will behave when used in an expression with the addition operator.
These methods are called user-defined operator implementations , and the
object-oriented terminology for defining operator behavior in a class is
called operator overloading .
Note: All operator overloading methods must be declared with both the
static and public keywords.

Overloading Unary Plus /Unary Minus:


If you need to overload the unary plus operator, the following characteristics
must be enjoyed by the method that is used to overload the unary plus.

A return type of your choice

The keyword operator

The operator being overloaded

A parameter list specifying a single parameter of the type of class or


structure containing the overloaded operator method

Overloading Prefix Increment and Decrement Operator:


If you need to overload the prefix increment or prefix decrement operators in
your class or structure, define a method with the following characteristics:

A return type specifying the type of class or operator method

The keyword operator

The operator being overloaded

A parameter list specifying a single parameter containing the


overloaded operator method

Example: Demonstrate Overloading of Unary Plus, Unary Minus, Prefix


Increment, Prefix Decrement.

Overloading Unary Plus

using System;
using System.Collections.Generic;

using System.Text;

namespace _CSharpApplication
{
class ClsOverLoadUnaryPlus
{
public int X;
public int Y;

public static ClsOverLoadUnaryPlus operator +( ClsOverLoadUnaryPlus


RValue)
{
ClsOverLoadUnaryPlus NewObj = new ClsOverLoadUnaryPlus ();
if (RValue.X < 0)
NewObj.X = -(RValue.X);
else
NewObj.X = RValue.X;
if (RValue.Y < 0)
NewObj.Y = -(RValue.Y);
else

NewObj.Y = RValue.Y;
return NewObj;
}
}
}

Overloading Unary Minus

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

namespace _CSharpApplication
{
class ClsOverLoadingUnaryMinus
{
public int X;
public int Y;
public static ClsOverLoadingUnaryMinus operator (
ClsOverLoadingUnaryMinus RValue)
{

ClsOverLoadingUnaryMinus objNew = new


ClsOverLoadingUnaryMinus ();
if (RValue.X > 0)
objNew.X = -(RValue.X);
else
objNew.X = RValue.X;
if (RValue.Y > 0)
objNew.Y = -(RValue.Y);
else
objNew.Y = RValue.Y;
return objNew;
}
}
}

Overloading Prefix Increment

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

namespace _CSharpApplication
{
class ClsOverloadingIncrement
{
public int X;
public int Y;

public static ClsOverloadingIncrement operator ++(


ClsOverloadingIncrement RValue)
{
ClsOverloadingIncrement objIncrement = new
ClsOverloadingIncrement ();
objIncrement.X = RValue.X + 1;
objIncrement.Y = RValue.Y + 1;
return objIncrement;
}
}
}

Overloading Prefix Decrement

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

namespace _CSharpApplication
{
class ClsOverLoadingDecrement
{
public int X;
public int Y;
public static ClsOverLoadingDecrement operator
( ClsOverLoadingDecrement RValue)
{
ClsOverLoadingDecrement objDecrement = new
ClsOverLoadingDecrement ();
objDecrement.X = RValue.X - 1;
objDecrement.Y = RValue.Y - 1;
return objDecrement;
}
}

Form2.cs

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

namespace _CSharpApplication
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();

private void button1_Click( object sender, EventArgs e)


{ //Overloading Unary Plus
ClsOverLoadUnaryPlus objUnaryPlus = new ClsOverLoadUnaryPlus
();
objUnaryPlus.X = -100;
objUnaryPlus.Y = 200;
MessageBox.Show((objUnaryPlus.X).ToString());
MessageBox.Show((objUnaryPlus.Y).ToString());
objUnaryPlus = +objUnaryPlus;
MessageBox.Show((objUnaryPlus.X).ToString());
MessageBox.Show((objUnaryPlus.Y).ToString());
}

private void button2_Click( object sender, EventArgs e)


{ //Overloading Unary Minus
ClsOverLoadingUnaryMinus objUnaryMinus = new
ClsOverLoadingUnaryMinus ();
objUnaryMinus.X = -10;
objUnaryMinus.Y = 20;

MessageBox.Show((objUnaryMinus.X).ToString());
MessageBox.Show((objUnaryMinus.Y).ToString());
objUnaryMinus = -objUnaryMinus;
MessageBox.Show((objUnaryMinus.X).ToString());
MessageBox.Show((objUnaryMinus.Y).ToString());
}

private void button3_Click( object sender, EventArgs e)


{ //Overlading Prefix Increment
ClsOverloadingIncrement objIncrement = new
ClsOverloadingIncrement ();
objIncrement.X = 100;
objIncrement.Y = 200;
MessageBox.Show((objIncrement.X).ToString());
MessageBox.Show((objIncrement.Y).ToString());
objIncrement = ++objIncrement;
MessageBox.Show((objIncrement.X).ToString());
MessageBox.Show((objIncrement.Y).ToString());
}

private void button4_Click( object sender, EventArgs e)

{ //Overloading Prefix Decrement


ClsOverLoadingDecrement objDecrement = new
ClsOverLoadingDecrement ();
objDecrement.X = 100;
objDecrement.Y = 200;
MessageBox.Show((objDecrement.X).ToString());
MessageBox.Show((objDecrement.Y).ToString());
objDecrement = --objDecrement;
MessageBox.Show((objDecrement.X).ToString());
MessageBox.Show((objDecrement.Y).ToString());
}
}
}

Output:

Click on Overloading Unary Plus:

Click on Overloading Unary Minus:

Click on Prefix Increment:

Click on Prefix Decrement:

Overloading Boolean Operator:


If you need to overload the true or false operators in your class or structure,
define a method with the following characteristics:

A return type of bool

The keyword operator

The operator being overloaded

A parameter list specifying a single parameter of the type of class or


structure containing the overloaded operator method

Overloading Conversion Operator:


You can also write operator overload methods that convert one type into
another type. If you need to define a new conversion operator in your class
or structure, define a method with the following characteristics:

The keyword implicit if the conversion is to be treated as an implicit


conversion, or the keyword explicit if the conversion is to be treated
as an explicit conversion

The keyword operator

A type specifying the target type of the conversion

A parameter list specifying the source type of the conversion

Overloading Binary Operators:

The operators that fall under this category are : Addition, Subtraction,
Division, Multiplication, Remainder, AND, OR, Exclusive OR, Shift left,
Shift Right, Equality, Inequality, Greater than, less than. If you need to
overload any of the binary operators in your class or structure, define a
method with the following characteristics:

A return type of your choice

The keyword operator

The operator being overloaded

A parameter list specifying two parameters, at least one of which must


be of the type of class or structure containing the overloaded operator
method

Example: Demonstrate Boolean Overloading, Conversion Overloading


and Binary Operators Overloading

ClsOverloadingBooleanOpertors.cs

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

namespace _CSharpApplication
{
class ClsOverloadingBooleanOpertors
{
public int X;
public int Y;

public static bool operator true ( ClsOverloadingBooleanOpertors RValue)


{
if ((RValue.X == 0) && (RValue.Y == 0))
return true ;
return false ;
}
public static bool operator false ( ClsOverloadingBooleanOpertors
RValue)
{
if ((RValue.X == 0) && (RValue.Y == 0))
return false ;
return true ;
}

}
}

ClsOverloadingConversion.cs

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

namespace _CSharpApplication
{
class ClsOverloadingConversion
{
public int X;
public int Y;
public static implicit operator double ( ClsOverloadingConversion
RValue)
{
double total_Distance;
double total_Sum;
total_Sum = (RValue.X * RValue.X) + (RValue.Y * RValue.Y);

total_Distance = System. Math .Sqrt(total_Sum);


return total_Distance;
}
}
}

ClsOverloadingEqualityInequality.cs

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

namespace _CSharpApplication
{
class ClsOverloadingEqualityInequality
{
public int X;
public int Y;
public static bool operator ==( ClsOverloadingEqualityInequality
objFirst,
ClsOverloadingEqualityInequality objSecond)

{
if (objFirst.X != objSecond.X)
return false ;
if (objFirst.Y != objSecond.Y)
return false ;
return true ;
}
public override bool Equals( object o)
{
return true ;
}
public override int GetHashCode()
{
return 0;
}
public static bool operator !=( ClsOverloadingEqualityInequality
objFirst, ClsOverloadingEqualityInequality objSecond)
{
if (objFirst.X != objSecond.X)
return true ;
if (objFirst.Y != objSecond.Y)

return true ;
return false ;
}
}
}

Form3.cs

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

namespace _CSharpApplication
{
public partial class Form3 : Form
{

public Form3()
{
InitializeComponent();
}

private void button1_Click( object sender, EventArgs e)


{ //Overloading True and False operator
ClsOverloadingBooleanOpertors objBoolean = new
ClsOverloadingBooleanOpertors ();
objBoolean.X = 20;
objBoolean.Y = 30;
if (objBoolean)
MessageBox.Show( "The point is at the origin." );
else
MessageBox.Show( "The point is not at the origin." );
}

private void button2_Click( object sender, EventArgs e)


{ //Overloadable Conversion Operator
double conDistance;

ClsOverloadingConversion objConversion = new


ClsOverloadingConversion ();
objConversion.X = 100;
objConversion.Y = 200;
conDistance = objConversion;
MessageBox.Show(conDistance.ToString());
}

private void button3_Click( object sender, EventArgs e)


{ //Overloading Equality/Inequality Operator
ClsOverloadingEqualityInequality MyFirstPoint = new
ClsOverloadingEqualityInequality ();
ClsOverloadingEqualityInequality MySecondPoint = new
ClsOverloadingEqualityInequality ();
ClsOverloadingEqualityInequality MyThirdPoint = new
ClsOverloadingEqualityInequality ();
MyFirstPoint.X = 100;
MyFirstPoint.Y = 200;
MySecondPoint.X = 500;
MySecondPoint.Y = 750;
MyThirdPoint.X = 100;
MyThirdPoint.Y = 200;

if (MyFirstPoint == MySecondPoint)
MessageBox.Show( "MyFirstPoint and MySecondPoint are at the same
coordinates." );
else
MessageBox.Show( "MyFirstPoint and MySecondPoint are not at the
same coordinates." );
if (MyFirstPoint == MyThirdPoint)
MessageBox.Show( "MyFirstPoint and MyThirdPoint are at the same
coordinates." );
else
MessageBox.Show( "MyFirstPoint and MyThirdPoint are not at the
same coordinates." );

}
}
}

Output:

Clicking on Overloading True/False Operator

Clicking on Overloading Conversion Operator

Clicking on Overloading Equality/Inequality Operator

Overloading Boolean Operator:


If you need to overload the true or false operators in your class or structure,
define a method with the following characteristics:

A return type of bool

The keyword operator

The operator being overloaded

A parameter list specifying a single parameter of the type of class or


structure containing the overloaded operator method

Overloading Conversion Operator:


You can also write operator overload methods that convert one type into
another type. If you need to define a new conversion operator in your class
or structure, define a method with the following characteristics:

The keyword implicit if the conversion is to be treated as an implicit


conversion, or the keyword explicit if the conversion is to be treated
as an explicit conversion

The keyword operator

A type specifying the target type of the conversion

A parameter list specifying the source type of the conversion

Overloading Binary Operators:


The operators that fall under this category are : Addition, Subtraction,
Division, Multiplication, Remainder, AND, OR, Exclusive OR, Shift left,
Shift Right, Equality, Inequality, Greater than, less than. If you need to
overload any of the binary operators in your class or structure, define a
method with the following characteristics:

A return type of your choice

The keyword operator

The operator being overloaded

A parameter list specifying two parameters, at least one of which must


be of the type of class or structure containing the overloaded operator
method

Example: Demonstrate Boolean Overloading, Conversion Overloading


and Binary Operators Overloading

ClsOverloadingBooleanOpertors.cs

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

namespace _CSharpApplication
{
class ClsOverloadingBooleanOpertors
{
public int X;
public int Y;

public static bool operator true ( ClsOverloadingBooleanOpertors RValue)


{
if ((RValue.X == 0) && (RValue.Y == 0))
return true ;
return false ;
}
public static bool operator false ( ClsOverloadingBooleanOpertors
RValue)

{
if ((RValue.X == 0) && (RValue.Y == 0))
return false ;
return true ;
}
}
}

ClsOverloadingConversion.cs

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

namespace _CSharpApplication
{
class ClsOverloadingConversion
{
public int X;
public int Y;

public static implicit operator double ( ClsOverloadingConversion


RValue)
{
double total_Distance;
double total_Sum;
total_Sum = (RValue.X * RValue.X) + (RValue.Y * RValue.Y);
total_Distance = System. Math .Sqrt(total_Sum);
return total_Distance;
}
}
}

ClsOverloadingEqualityInequality.cs

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

namespace _CSharpApplication
{
class ClsOverloadingEqualityInequality

{
public int X;
public int Y;
public static bool operator ==( ClsOverloadingEqualityInequality
objFirst,
ClsOverloadingEqualityInequality objSecond)
{
if (objFirst.X != objSecond.X)
return false ;
if (objFirst.Y != objSecond.Y)
return false ;
return true ;
}
public override bool Equals( object o)
{
return true ;
}
public override int GetHashCode()
{
return 0;
}

public static bool operator !=( ClsOverloadingEqualityInequality


objFirst, ClsOverloadingEqualityInequality objSecond)
{
if (objFirst.X != objSecond.X)
return true ;
if (objFirst.Y != objSecond.Y)
return true ;
return false ;
}
}
}

Form3.cs

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

namespace _CSharpApplication
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}

private void button1_Click( object sender, EventArgs e)


{ //Overloading True and False operator
ClsOverloadingBooleanOpertors objBoolean = new
ClsOverloadingBooleanOpertors ();
objBoolean.X = 20;
objBoolean.Y = 30;
if (objBoolean)
MessageBox.Show( "The point is at the origin." );
else
MessageBox.Show( "The point is not at the origin." );

private void button2_Click( object sender, EventArgs e)


{ //Overloadable Conversion Operator
double conDistance;
ClsOverloadingConversion objConversion = new
ClsOverloadingConversion ();
objConversion.X = 100;
objConversion.Y = 200;
conDistance = objConversion;
MessageBox.Show(conDistance.ToString());
}

private void button3_Click( object sender, EventArgs e)


{ //Overloading Equality/Inequality Operator
ClsOverloadingEqualityInequality MyFirstPoint = new
ClsOverloadingEqualityInequality ();
ClsOverloadingEqualityInequality MySecondPoint = new
ClsOverloadingEqualityInequality ();
ClsOverloadingEqualityInequality MyThirdPoint = new
ClsOverloadingEqualityInequality ();
MyFirstPoint.X = 100;

MyFirstPoint.Y = 200;
MySecondPoint.X = 500;
MySecondPoint.Y = 750;
MyThirdPoint.X = 100;
MyThirdPoint.Y = 200;
if (MyFirstPoint == MySecondPoint)
MessageBox.Show( "MyFirstPoint and MySecondPoint are at the same
coordinates." );
else
MessageBox.Show( "MyFirstPoint and MySecondPoint are not at the
same coordinates." );
if (MyFirstPoint == MyThirdPoint)
MessageBox.Show( "MyFirstPoint and MyThirdPoint are at the same
coordinates." );
else
MessageBox.Show( "MyFirstPoint and MyThirdPoint are not at the
same coordinates." );

}
}
}

In socket-based network programming, you do not directly access the


network interface device to send and receive packets. Instead, an
intermediary file descriptor is created to handle the programming interface
to the network. The special file descriptors used to reference network
connections are called sockets . The socket defines the following:

A specific communication domain, such as a network connection or a


Unix Interprocess Communication (IPC) pipe

A specific communication type, such as stream or datagram

A specific protocol, such as TCP or UDP

After the socket is created, it must be bound to either a specific network


address or port on the system, or to a remote network address and port. Once
the socket is bound, it can be used to send and receive data from the
network.
Network Addresses
After the socket is created, it must be bound to a network address/port pair.
UNIX offers an IP-specific address structure, sockaddr_in , which uses the
following elements. Using the sockaddr_in structure requires placing the
appropriate IP address and port values in the proper data element.
1. sin_family An address family, defined as a short type
2. sin_port A port number, defined as a short type
3. sin_addr An address, defined as a long type (4-byte) IP address
4. sin_data 8 bytes of padding.

.NET defines two classes in the System.Net namespace to handle various


types of IP address information.The classes are IPAddress and IPEndPoint
IPAddress object is used to represent a single IP address. This value can be
used in the various socket methods to represent the IP address.

IPAddress Methods:-

Method

Description
Compares two IP addresses.

Equals
Returns a hash value for an IPAddress object.
GetHashCode
Returns the type of the IP address instance.
GetType
Converts an IP address from host byte order to
HostToNetworkOrder network byte order.

IsLoopBack

Indicates whether the IP address is considered the


loopback address.

Converts an IP address from network byte order to


NetworkToHostOrder host byte order.
Converts a string to an IPAddress instance.
Parse

ToString

Converts an IPAddress to a string representation of the


dotted decimal format of the IP address.

IPEndPoint: object is used when binding sockets to local addresses, or


when connecting sockets to remote addresses. The following two
constructors are used to create IPEndPoint instances:

IPEndPoint (long address , int port )

IPEndPoint(IPAddress address , int port )

PEndPoint Methods:

Method

Description
Creates an EndPoint object from a SocketAddress object

Create
Returns the type of the IPEndPoint instance
GetType
Compares two IPEndPoint objects
Equals

Serialize

Creates a SocketAddress instance of the IPEndPoint


instance

ToString

Creates a string representation of the IPEndPoint


instance
Returns a hash value for an IPEndPoint object

GetHashCode

Example: Demonstrate Socket Programming


Form4.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;

using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;

namespace _CSharpApplication
{
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
}

private void button1_Click( object sender, EventArgs e)


{ //Introduction to IP Addresses.
IPAddress _address1 = IPAddress .Parse( "192.168.1.1" );
IPAddress _address2 = IPAddress .Broadcast;
IPAddress _address3 = IPAddress .Loopback;

IPAddress _address4 = IPAddress .None;


IPAddress _address5 = IPAddress .Any;
IPHostEntry _hostName = Dns .GetHostEntry( Dns .GetHostName());
IPAddress _myMachine = _hostName.AddressList[0];
if ( IPAddress .IsLoopback(_address3))
lstAddresses.Items.Add( "Loopback address is: " + _address3.ToString());
else
lstAddresses.Items.Add( "Error obtaining the LoopbackAddress" );
lstAddresses.Items.Add( "Local IP address is: " + _myMachine.ToString());

if (_myMachine == _address3)
lstAddresses.Items.Add( "Loopback Address Is Same AsLocal Address.\n" );
else
lstAddresses.Items.Add( "The loopback address is not the local
address.\n" );
lstAddresses.Items.Add( "Given Address is: " + _address1.ToString());
lstAddresses.Items.Add( "Broadcast address: " + _address2.ToString());
lstAddresses.Items.Add( "ANY address is: " + _address5.ToString());
lstAddresses.Items.Add( "NONE address is: " + _address4.ToString());
}

private void button2_Click( object sender, EventArgs e)


{ //Introduction To IPEndPoint
IPAddress test1 = IPAddress .Parse( "192.168.1.1" );
IPEndPoint _endPoint = new IPEndPoint (test1, 8000);

lstIPEndPoint.Items.Add( "IPEndPoint is ::" + _endPoint.ToString());


lstIPEndPoint.Items.Add( "AddressFamily is ::"
+_endPoint.AddressFamily);
lstIPEndPoint.Items.Add( "Address is :: " + _endPoint.Address);
lstIPEndPoint.Items.Add( "Port is :: " + _endPoint.Port);
lstIPEndPoint.Items.Add( "Min port number is :: " + IPEndPoint .MinPort);
lstIPEndPoint.Items.Add( "Max port number is :: " +IPEndPoint .MaxPort);
_endPoint.Port = 80;
lstIPEndPoint.Items.Add( "Changed IPEndPoint is :: " +
_endPoint.ToString());
SocketAddress _socketAddress = _endPoint.Serialize();
lstIPEndPoint.Items.Add( "SocketAddress is :: " +
_socketAddress.ToString());
}
}}

Output:

Clicking on both the buttons the output will be:

To simplify the unwieldy state of computer naming, the Domain Name


System (DNS) was created. It allows the master host database to be split up
and distributed among multiple systems on the Internet. DNS uses a
hierarchical database approach, creating levels of information that can be
split and stored on various systems throughout the Internet.
DNS Structure
The structure of a hierarchical database is similar to an organization chart
with nodes connected in a treelike manner (that's the hierarchical part). The
top node is called the root . The root node does not explicitly show up in
Internet host addresses, so it is often referred to as the nameless node.
Multiple categories were created under the root level to divide the database
into pieces called domains . Each domain contains DNS servers that are
responsible for maintaining the database of computer names for that area of
the database (that's the distributed part).

The first (or top) level of distribution is divided into domains based on country codes.
Additional top-level domains for specific organizations were created to prevent the
country domains from getting overcrowded.

Domain

Description
U.S. military sites

.mil
Commercial organizations
.com
Educational institutions
.edu
U.S. government organizations
.gov
Internet Service Providers (ISPs)
.net
Other U.S. organizations (such as local governments)
.us
Nonprofit organizations
.org
Canadian organizations
.ca
German organizations
.de
Organizations from other countries
[other countries]

Using DNS
The last way to determine system IP information is to utilize the C# DNS
(Domain Name System) classes. DNS can be used to obtain Internet

hostnames and IP Addresses. The C# System.Net namespace contains the


DNS class, which comprises several methods that allow you to obtain DNS
information about hosts. The GetHostName() method retrieves the hostname
of the local system. The GetHostByName() method attempts to find the IP
address of a hostname.

DNS Configuration
When your C# application is running on a customer's system, you have no
guarantee that there are any DNS servers configured. You can find out what
(if any) DNS servers are configured by using the .NET Registry class
methods to examine the DNS Registry values.
Fortunately, all Windows platforms store the DNS server information in the
same place:
HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
Registry Data Values for DNS Servers

Data Value

DatabasePath

Domain

NameServer

Description

The location of the host's file

The name of the system's domain

The list of DNS servers

Hostname

The name of the system's DNS host

SearchList

A list of DNS domains to append to


the end of hostnames in DNS name
searches

The value of most interest here is NameServer . This should contain a single
string value representing all the configured DNS servers, separated by
spaces. The primary DNS server will be listed first, followed by the alternate
servers.

Example: Demonstrate DNS and its Configuration in Registry


using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using Microsoft.Win32;

namespace _CSharpApplication
{
public partial class Form6 : Form
{
public Form6()
{
InitializeComponent();
}

private void button1_Click( object sender, EventArgs e)

{ //Demonstrate DNS..
string _hostName = Dns .GetHostName();
lstDNS.Items.Add( "Local hostname :: " + _hostName);
IPHostEntry _ipHostEntry = Dns .GetHostByName(_hostName);
foreach ( IPAddress _address in _ipHostEntry.AddressList)
{
lstDNS.Items.Add( "IP Address ::" + _address.ToString());
}
}

private void button2_Click( object sender, EventArgs e)


{ //DNS Configuration in Registry
RegistryKey start = Registry .LocalMachine;
string DNSservers =
@"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters" ;
RegistryKey DNSserverKey = start.OpenSubKey(DNSservers);
if (DNSserverKey == null )
{
lstDNSConfiguration.Items.Add( "Unable to open DNS servers
key" );
return ;

}
string serverlist = ( string )
DNSserverKey.GetValue( "NameServer" );
lstDNSConfiguration.Items.Add( "DNS Servers: " + serverlist);
DNSserverKey.Close();
start.Close();
char [] token = new char [1];
token[0] = ' ' ;
string [] servers = serverlist.Split(token);
foreach ( string server in servers)
{
lstDNSConfiguration.Items.Add( "DNS server: " + server);
}
}
}
}
File access in .NET is generally handled with stream objects. In this section,
we will discuss about the two classes BinaryWriter and BinaryReader to
demonstrate the file handling in C#. The BinaryReader and BinaryWriter
classes support binary file access. These classes permit binary operations to
and from streams.

BinaryWriter
The BinaryWriter class allows primitive data types to be written to streams;
and with the use of subclassing, you can override the methods of this class
and fulfill your own unique character encoding requirements. The following
table will summarize the properties of the class:-

Name

Type

Purpose

BaseStream Property Allow access to binary writer underlying stream.

Close

Method Close the Binary writer class and the underlying


stream.

Flush

Method Flushes out all data to the underlying stream and


then clears buffers.

Seek

Method Sets the current position within the current stream.

Write

Method This overloaded method writes a value out to the


current stream.

BinaryReader
The BinaryReader class, much like the BinaryWriter class, relies on a
FileStream object to read files .

Method

Close

PeekChar

ReadBoolean

Description

Close the binary reader object and the base stream.

Reads the next available byte from the stream but does not
advance the byte or character position within the file.

Reads a Boolean [True/False] value from the stream.

ReadByte

Reads a single byte from the stream. There is also a


readbytes method for specifying the number of bytes to
read.

ReadChar

Reads a single char value from the stream. There is also a


readchars method for specifying the number of chars to
read.

ReadInt16

Reads an integer value (2 bytes).

ReadInt32

Reads a long value (4 bytes).

ReadInt64

Reads an eight-byte signed integer.

Example: Demonstrate working with files

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace _CSharpApplication
{
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();

private void button1_Click( object sender, EventArgs e)


{ //Writing to the file
FileStream myFStream = new FileStream
( "G:\\2CSharpApplication\\Test.txt" , FileMode
FileAccess .ReadWrite);

.OpenOrCreate,

BinaryWriter binWrit = new BinaryWriter (myFStream);


string testString = "Writing into a File..This is a test Value." ;
binWrit.Write(testString);
binWrit.Close();
myFStream.Close();
}

private void button2_Click( object sender, EventArgs e)


{ //Reading from the file.
long imageWidth = 0;
long imageHeight = 0;
int imagePlanes = 0;
int imageBitCount = 0;
string [] cma = Environment .GetCommandLineArgs();

if (cma.GetUpperBound(0) >= 1)
{
FileStream myFStream = new FileStream (cma[1], FileMode .Open,
FileAccess .Read);
BinaryReader binRead = new BinaryReader (myFStream);
binRead.BaseStream.Position=0x12;
imageWidth = binRead.ReadInt32();
imageHeight= binRead.ReadInt32();
imagesPlanes= binRead.ReadInt16();
imagesBitCount = binRead.ReadInt16();
Console .WriteLine( "[{0}] {1}x{2} {3}- bit" ,cma[1], imageWidth,
imageHeight, imageBitCount);
binRead.Close();
myFStream.Close();
}
}
private void button3_Click( object sender, EventArgs e)
{ //Copying File.
string [] strcla = Environment .GetCommandLineArgs();
if (strcla.GetUpperBound(0) == 2)
{

FileInfo cpyfi = new FileInfo (strcla[1]);


cpyfi.CopyTo(strcla[2], true );
MessageBox .Show( "Copied " + cpyfi.Length + " bytes." );
}
else
MessageBox .Show( "Usage: cp <input file> <output file>" );
}

private void button4_Click( object sender, EventArgs e)


{ //Deleting File.
string [] strcla = Environment .GetCommandLineArgs();
if (strcla.GetUpperBound(0) == 1)
{
FileInfo delfi = new FileInfo (strcla[1]);
delfi.Delete();
MessageBox .Show( "File : " + strcla[1]);
MessageBox .Show( "Attributes: " + delfi.Attributes.ToString());
MessageBox .Show( "File Deleted..." );
}
else

MessageBox .Show( "Usage: rm <filename>" );


}

private void button5_Click( object sender, EventArgs e)


{ //Moving File.
string [] strcla = Environment .GetCommandLineArgs();
if (strcla.GetUpperBound(0) == 2)
{
FileInfo movfi = new FileInfo (strcla[1]);
movfi.MoveTo(strcla[2]);
MessageBox .Show( "File Created : " +movfi.CreationTime.ToString());
MessageBox .Show( "Moved to : " + strcla[2]);
}
else
MessageBox .Show( "Usage: mv <source file> <destination file>" );
}
}
}
An interesting feature of the C# compiler is to generate XML documentation
from the comments. C# compiler reads specially formatted comments and

generates XML documentation from the comments. You can then displays
this XML on the Web to provide an extra level of documentation to
developers who need to understand the structure of your applications.

Pre-requisites to generate XML documentation from the comments are:

Use three slashes for comments(///). The C# compiler does not


generate any XML Documentation for any comments that do not
begin with three slashes. Nor does the C# compiler generates any
XML documentation for regular, multi line, comments.

Use the /doc option of the C# compiler to specify the name of the file
that should contain the generated XML documentation.

Example: Demonstrate XML documentation from Comments

Step1: In the first step we create the C# code file.

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace _CSharpApplication

{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// Developed By : C# Team
/// Developed On : 21 Oct,07
/// </summary>
[ STAThread ]
static void Main ()
{
Application .EnableVisualStyles();
Application .SetCompatibleTextRenderingDefault( false );
System.Console.WriteLine( "StartUp for C# World!" );
}
}
}
Step2: The following command is used to generate the help file. The
command will create two files i.e. Program.exe and other is
ProgramHelpFile.xml .

Command: csc /doc: HelpFile.xml ProgramFile.cs

Output:The following xml will be generated by the above command.

ProgramHelpFile.xml

<?xml version="1.0"?>
<doc>
<assembly>
<name>Program</name>
</assembly>
<members>
<member name="M:_CSharpApplication.Program.Main">
<summary>
The main entry point for the application.
Developed By : C# Team
Developed On : 21 Oct,07
</summary>

</member>
</members>
</doc>

Note: -Main portion of XML documentation is found in <member> element:


This element contains one <member> tag for each documented item in the
source code. The <member> tag contains one attribute, name, which names
the member being documented. The value of the name attribute starts with a
one-letter prefix describing the type of information being described. Options
for the first letter of the name attribute's value and its meaning. <member>
name = Attribute Prefixes >

Other Important Tags:

The following is the list of more help file tags which can be used in the C#.
1. <c>:- T ag to indicate that a small part of your comment should be
treated as code. Style sheets may use this element to display the code
portion of your comment E.g. /// This is the <c> Main ()</c> function
for the /// Program class.
2. <code>:- Tag to indicate that multiple lines of text in your comments
should be treated as code: E.g.
/// <code>
/// Argument[0]: command line argument 1
/// Argument[1]: command line argument 2
/// Argument[2]: command line argument 3
/// </code>

3. <exception>:- You can use the <exception> tag to document any


exceptions that may be raised from the member's code. The
<exception> tag must contain an attribute called cref whose value
specifies the type of exception being documented. The cref attribute
value must be enclosed in quotes. The text of the element describes
the conditions under which the exception is thrown: E.g.
/// <exception cref="System.Exception">
/// Raised if the input is less than 0.
/// </exception>
4. <permission>:- Use the <permission> tag to document the
permissions available on a given function or variable. Access to a
class's code and data can mean access to all of the code or it can be
restricted to a certain subset of code. You can use the <permission>
tag to document the availability of your code and data. The
<permission> tag makes use of one attribute: cref. The value of the
cref element must name the function or variable whose permissions
are being documented: E.g.
/// <permission name="Main()">
/// Everyone can access Main ().
/// </permission>
5. <remarks>:- Use the <remarks> tag to add information about an item.
The <remarks> element is great for providing an overview of a
method or variable and its usage. The <remarks> tag carries no
attributes and its text contains the remarks: E.g.
/// <remarks>
/// The Main () function is the entry point into the
/// application. The CLR will call Main () to start
/// the application after the application loads
/// </remarks>

Code access security is a feature of .NET that manages code, dependent on


our level of trust. If the CLR trusts the code enough to allow it to run, it will
begin executing the code. Depending on the permissions provided to the
assembly, however, it might run within a restricted environment. If the code

is not trusted enough to run, or if it runs but then attempts to perform an


action, for which it does not have the relevant permissions, a
SecurityException is thrown. The code access security system means that we
can stop malicious code running, but we can also allow code to run within a
protected environment where we are confident that it cannot do any damage.

CAS is part of .Net security model that determines whether or not a piece of
code is allowed to run and what resources it can use while running. CAS
grants rights to program depending on the security configuration of the
machine. For e.g. the program has rights to edit or create a new file but the
security configuration of machine does not allow the program to delete a
file.

Code access security is based on two concepts Code Groups and


Permissions. The following sections will discuss both in detail.

Code Group
Code Group is the concept of bringing together the code with similar
characteristics. Two examples for code groups are Internet and Intranet. The
group Internet defines code that is sourced from the Internet, the group
Intranet defines code sourced from the LAN. Code groups have an entry
requirement called membership condition . Each code group has one, and
only one, membership condition.

Following is the available list of code group memberships:

Zone: The region from which the code originated. A zone is one of the
commonly used condition. A zone is the region of origin of a piece of
code and refers to one of the following: My Computer, Internet,
Intranet, Trusted, or not trusted.

Site: The Web site from which the code originated.

Strong Name: A unique, verifiable name for the code.

Publisher: The publisher of the code.

URL: The specific location from which the code originated.

Hash Value: The hash value for the assembly.

Skip Verification: This condition requests that it bypasses code


verification checks.

Application Directory: The location of the assembly within the


application.

All Code: All code fulfills this condition.

Custom: A user-specified condition.

Code groups are arranged hierarchically with the All Code membership
condition at the root.

Permissions

Permissions are the actions we allow each code group to perform? For
example, permissions include able to access the user interface and able to
access local storage. The system administrator usually manages the
permissions at the enterprise, machine, and user levels.
A thread is a sequence of execution in a program. All our C# programs up to
this point have one entry pointthe Main () method. Execution starts with
the first statement in the Main () method and continues until that method
returns. A thread is the basic unit to which the operating system allocates
processor time.

Processes are made up of one or more threads. A thread is defined as a single


flow of operation within a program. When a program executes on the CPU,
it traverses the program statements in a single thread until the thread is
complete. A multithreaded application distributes functions among multiple
program flows, allowing two or more paths of execution to occur. Each path
of execution is a separate thread.

Multi-tasking: It's a feature of modern operating systems with which we can


run multiple programs at same time example word, excel etc

Multi-Threading: Multi-threading forms subset of multi-tasking instead of


having to switch between programs this feature switches between different
parts of the same program. Example we are writing a word document and at
the same time word is doing a spell check in background.
Multithreaded programs create their own threads that can be executed
separately from the main thread of the program. All threads created by the
primary thread share the same memory address space as the primary thread.
Often the secondary threads are used to perform computationally intensive
functions, allowing the main thread to continue responding to Windows
events. Without the secondary threads, the user could not select anything

from the menu or click any buttons while an application computed a


mathematical function

System.Threading: This namespace has all the classes that are related to
implement threading. Any .Net application who wants to implements
threading has to import this namespace.
Note: In .Net program, there are always at least two threads running, i.e. one
is the main program and other is the garbage collector.

States:
Threads have several operational states, which are enumerated using the
.NET Thread State enumeration, found in the System.Threading namespace.

Initialized: The thread has been initialized but not started.

Ready: The thread is waiting for a processor.

Running: The thread is currently using the processor.

Standby: The thread is about to use the processor.

Terminated: The thread is finished and is ready to exit.

Transition: The thread is waiting for a resource other than the


processor.

Unknown: The system is unable to determine the thread state.

Wait: The thread is not ready to use the processor

The Thread Class

Use the Thread class to create a new Thread object, which produces a new
thread within the current process. The format of the Thread constructor is as
follows, where start is a ThreadStart delegate:
Thread (ThreadStart start)
The ThreadStart delegate points to the method that will be performed within
the new thread.

E.g. Thread newthread= new Thread (new ThreadStart (anyMethod));


Void anyMethod () {}
After the Thread object is created, it can be controlled using various Thread
class methods, which are as under:

Abort (): Terminate the thread.

Equals (): Determines whether two thread objects are same.

GetHashCode (): Get a unique representation for the thread.

GetType (): Get the type of the current thread.

Interrupt (): Interrupts a thread that is in a wait state.

Join (): Blocks the calling thread until the thread terminates.

Resume (): Resumes a thread that has been suspended.

Start (): Change the state of the thread to running.

Suspend (): Suspend the execution of the thread.

ToString (): gets a string representation of the Thread object.

Thread priority: The thread priority determines the order in which thread
has to execute. The thread priority can be changed by using
Threadname.Priority = ThreadPriority.Highest.
Different levels of priority provided by .Net:

ThreadPriority.Highest

ThreadPriority.AboveNormal

ThreadPriority.Normal

ThreadPriority.BelowNormal

ThreadPriority.Lowest

Thread.Sleep (): Thread execution can be paused by calling the


Thread.Sleep method. This method takes an integer value that determines
how long the thread should sleep.

Example: Demonstrate Threading

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;
using System.Threading;

namespace ConsoleApplication1
{
class Program1

{
static void Main ( string [] args)
{
Program1 ts = new Program1 ();
}
public Program1()
{
int i;
Thread firstThread = new Thread ( new ThreadStart (FirstMethod));
Thread secondThread = new Thread ( new ThreadStart
(SecondMethod));
firstThread.Start();
secondThread.Start();
for (i = 0; i < 10; i++)
{
Console.WriteLine( "Main: {0}" , i);
Thread .Sleep(1000);
}
}
void FirstMethod()

{
int i;
for (i = 0; i < 10; i++)
{
Console.WriteLine( " First thread: {0}" , i);
Thread .Sleep(2000);
}
}
void SecondMethod()
{
int i;
for (i = 0; i < 10; i++)
{
Console.WriteLine( " Second thread2: {0}" , i);
Thread .Sleep(3000);
}
}
}
}

When writing applications for international distribution, different cultures


and regions must be kept in mind. Different cultures have diverging
calendars and use different number and date formats, and also the sort order
with the letters A-Z may lead to various results. To make applications fit for
global markets you have to globalize and localize them.

Globalization is about internationalizing applications: preparing


applications for international markets. With globalization, the
application supports number and date formats depending on the
culture, different calendars, and so on.

Localization is about translating applications for specific cultures. For


translations of strings, you can use resources.

.NET supports globalization and localization of Windows and Web


applications. To globalize an application you can use classes from the
namespace System.GlobalizationSystem.Resources. whereas to localize an
application you can use resources that are supported by the namespace

System.Globalization
The System.Globalization namespace holds all culture and region classes to
support different date formats, different number formats, and even different
calendars that are represented in classes such as Gregorian calendar, Hebrew
Calendar, Japanese Calendar, and so on. Using these classes you can display
different representations depending on the user's locale.

Cultures and Regions


The world is divided into multiple cultures and regions, and applications
have to be aware of these cultural and regional differences. RFC 1766
defines culture names that are used worldwide depending on a language and

a country or region. Some examples are en-AU, en-CA, en-GB, and en-US
for the English language in Australia , Canada , United Kingdom , and the
United States .

Note:- Most Important class in System.Globaliation namespace is


CultureInfo [Represents a Culture]

Example: Demonstrate CultureInfo

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;
using System.Threading;
using System.Globalization;

namespace ConsoleApplication1
{
class Program1
{
static void Main ( string [] args)
{

int val = 1234567890;


string name = "visualbuilder" ;
//Culture of the Current Thread
Console .WriteLine(val.ToString( "N" ));
//use IFormatProvider
Console .WriteLine(val.ToString( "N" , new CultureInfo ( "fr- FR" )));
//Change the culture of the thread
Thread .CurrentThread.CurrentCulture = new CultureInfo ( "de- DE" );
Console .WriteLine(val.ToString( "N" ));
}
}
}

Windows Registry is a central database for application configuration settings


and other information required by the applications. The Windows Registry is
a data repository that exists on each computer in Windows Operating
systems. Both the system and application programs use this repository to
store information needed at runtime. For example, the system stores file
associations (the applications or command lines associated with each known
file extension) in the Registry. Applications often use the Registry to store
information such as users' option settings and data file pathnames.

Note:- If you've never open Windows registry, you can see it by running
regedit from command line

.NET Framework Library provides two classes - Registry and RegistryKey to


work with the windows registry. These classes are defined in
Microsoft.Win32 namespace. So before using these classes, you need to add
reference to this namespace.

Registry Class:
The Registry class contains members to provides access to registry keys. We
can define registry keys in the following order.

CurrentUser - Stores information about user preferences.

LocalMachine - Stores configuration information for the local


machine.

ClassesRoot - Stores information about types (and classes) and their


properties.

Users - Stores information about the default user configuration.

PerformanceData - Stores performance information for software


components.

CurrentConfig - Stores non-user-specific hardware information.

DynData - Stores dynamic data.

The Registry class members are described in the following table.

ClassesRoot

Returns a RegistryKey type which provides access to


HKEY_CLASSES_ROOT key.

LocalMachine Returns a RegistryKey type which provides access to


HKEY_LOCAL_MACHINE key.

CurrentConfig Returns a RegistryKey type which provides access to


HKEY_CURRENT_CONFIG key.

DynData

Returns a RegistryKey type which provides access to


HKEY_DYN_DATA key.

CurrentUser

Returns a RegistryKey type which provides access to


HKEY_CURRENT_USER key

PerformanceData Returns a RegistryKey type which provides access to


HKEY_PERFORMANCE_DATA key.

Users

Returns a RegistryKey type which provides access to


HKEY_USERS key.

RegistryKey Class :
The RegistryKey class contains members to add, remove, replace, and read
registry data. Some of its common methods and properties are defined in the
following table.

Properties:
Name - Represents the name of the key.

SubKeyCount - Represents the count of subkeys at the base level, for


theCurrent key.
ValueCount - Represents the count of values in the key.

Methods:

GetValueNames Retrieves an array of strings that contains all the value


names associated with this key.

GetValue

OpenSubKey

Returns the specified value.

Opens a subkey.

GetSubKeyNames Returns an array of strings that contains all the subkey


names.

DeleteSubKeyTree Deletes a subkey and any children.

DeleteSubKey

Deletes the specified subkey.

CreateSubKey

Creates a new subkey if not exists, otherwise opens an


existing subkey.

SetValue

DeleteValue

Close

Sets the specified value.

Deletes the specified value from a key.

Closes the key.

Example:- Working with Windows Registry.

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click( object sender, EventArgs e)


{ //Adding a Key and Value in Registry
RegistryKey key = Registry
.LocalMachine.OpenSubKey( "Software" , true );
//Create Key inside the software folder
RegistryKey newkey = key.CreateSubKey( "NewTestKeyAdded" );
//User Can also set the value for this Key
newkey.SetValue( "NewTestKeyAdded" , "ValueForThisTestKey" );
MessageBox.Show( "Key/Value is added in the Registry..." );
}

private void button2_Click( object sender, EventArgs e)

{ //Retrieving Data From Registry


RegistryKey pRegKey = Registry .LocalMachine;
pRegKey = pRegKey.OpenSubKey( "HARDWARE\\
DESCRIPTION\\System\\FloatingPointProcessor\\0" );
Object valueOfKey = pRegKey.GetValue( "Identifier" );
MessageBox.Show( "Key Value is :: " + valueOfKey);
}

private void button3_Click( object sender, EventArgs e)


{ //Deleting Key/Value from Registry

RegistryKey delKeyValue = Registry


.LocalMachine.OpenSubKey( "Software\\" );
delKeyValue.DeleteValue( "ValueForThisTestKey" );
// Delete the key from the registry.
RegistryKey delSubKey = Registry
.LocalMachine.OpenSubKey( "Software" , true );
delSubKey.DeleteSubKey( "NewTestKeyAdded" );
MessageBox.Show( "Deleting Key/Value in the Registry" );
}
}

}
The coming section will discuss about some more classes used for
Globalization in C#.

Resources and ResourceWriter

Resources such as pictures or string tables can be put into resource files or
satellite assemblies. Such resources can be very helpful when localizing
applications, and .NET has built-in support to search for localized resources.
A resource file can be a text file or a .resx file or XML file. This file contains
the key/value pairs. Where the keys are used in the program and at run time
they are replaced with the values that is corresponding to each key. For
example:-

Name = Jim Tire


Address = USA
Author = Puppet
Publisher = Jim Toe

Note:-ResGen.exe utility is used to create a resource file out of this


test.txt file. the command Resgen test.txt will create the text.txt resource
file and Resgen test.txt test.resx will createtthe XML file from the test.txt file.

ResourceWriter
This class under the System.Resources namespace is used to create the
resource file through the programming. The below example will create the

object of the ResourceWriterAddResource() method. and then we can use the


same object to add upto 2GB of resources. We have to just supply the
key/value pair to the object's

Example: Demonstrate ResourceWriter

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;
using System.Threading;
using System.Globalization;
using System.Resources;

namespace ConsoleApplication1
{
class Program1
{
static void Main ( string [] args)
{
ResourceWriter rw = new ResourceWriter ( "RWDemo.resources" );

rw.AddResource( "Name " , "VisualBuilder" );


rw.AddResource( "Adress" , " UK " );
rw.AddResource( "Hobby" , "Cricket" );
rw.AddResource( "Favourite Country" , " Australia " );
rw.AddResource( "Player" , "Sunny" );
rw.Close();
}
}
}

Output:

This will create RWDemo.resources file, which contains the key/value pairs.
The Close() method of the ResourceWriter class automatically calls
ResourceWriter.Generate() to finally write the resources to the file
RWDemo.resources.

Using Resource File in an Application

We can add resource files to assemblies using the assembly generation tool
al.exe, using the /embed option or using the c# compiler with /resource
option or directly using the VS.Net. The following are the steps to use the
resource files in C# application.

1. Open the application


2. Use the context menu of the solution explorer (Add >> Add Existing
Item)
3. Locate the path where the resource file is situated.
4. If you check the Resource after adding it to the projects, its
BuildAction is Embedded Resource, this means the resource is
embedded to the output assembly.
5. You can view the resource file using the ILDasm.exe utility by
checking it in the assembly manifest.
6. To access the embedded resources, use the Resource Manager class
from the System.Resources namespace.
7. You can pass the assembly that has the resources as an argument to
the constructor of the Resource Manager class
8. Once you include the resource file in the application use the Resource
Manager and load the resource file into this.

Example: Demonstrate Usage of Resource File

using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Resources;

namespace cSHARPEXAMPLES
{
public partial class Form22 : Form
{
public Form22()
{
InitializeComponent();
}

private void button1_Click( object sender, EventArgs e)


{ //Using Resource File

System.Resources. ResourceManager rm;


Assembly assembly = Assembly .GetExecutingAssembly();
rm = new ResourceManager ( "cSHARPEXAMPLES.RWDemo" ,
assembly);
txtName.Text = rm.GetString( "Name " );
txtAddress.Text=rm.GetString( "Adress" );
txtHobby.Text = rm.GetString( "Hobby" );
txtFCountry.Text = rm.GetString( "Favourite Country" );
txtPlayer.Text = rm.GetString( "Player" );
}
}
}
The core function of a Windows Service is to run an application in the
background. One of the ways that it differs from an windows application in
that a Windows Service starts before any user logs in to the system (if it has
been setup to start at boot up), although it can also be setup in such a way
that it requires user to start it manually. A Windows Service also has its own
process hence it runs very efficiently. Normally a Windows Service will not
have a user interface for a simple reason it can be run even if no one is
logged on to the system but this is not a rule, you can still have a Windows
Service with a user interface.

Creating a Windows Service:

Step 1:- Open VS 2005, Click on File > Projects.

Step 2:- This will open up a project and clicking on the hyperlink that is
there on the page, you will be able to open the code behind page where you
can code for the web service.

Step 3:- Add Functionality to the web service that you have created. There
are two overridden function i.e. OnStart and OnStop. The OnStart
function executes when you start your service and the OnStop function gets
execute when you stop a service.

//OnStart
protected override void OnStart( string [] args)
{}

//OnStop
protected override void OnStop()
{}

Step 4:- Install and Run the Service: For Installation of the service on the
computer, one need to have the administrator rights to install the service on

the computer. The installUtil tool is provided by with the .Net framework to
install the application.

Note:- The use should have administrator rights to install the utility. If the
utility is not installed then it will display a popup when you run the
program.

Example: Demonstrate Windows Services.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;

namespace winServiceFirst
{
public partial class OTestService : ServiceBase
{
public OTestService()
{
InitializeComponent();
}

protected override void OnStart( string [] args)


{
//This will be printed at the start of the service....
FileStream fs = new FileStream
( @"C:\windowServiceTest\trackerForWebService.txt" ,
.OpenOrCreate, FileAccess .Write);

FileMode

StreamWriter m_streamWriter = new StreamWriter (fs);


m_streamWriter.BaseStream.Seek(0, SeekOrigin .End);
m_streamWriter.WriteLine( " ************************** \n" );
m_streamWriter.WriteLine( " mcWindowsService: Service Started \n" );
m_streamWriter.WriteLine( " ************************** \n" );

m_streamWriter.Flush();
m_streamWriter.Close();
}

protected override void OnStop()


{ // TODO: Add code here to perform any tear-down necessary to stop
your service.
//This will be printed at the end of the service...
FileStream fs = new FileStream
( @"C:\windowServiceTest\trackerForWebService.txt" , FileMode
.OpenOrCreate, FileAccess .Write);
StreamWriter m_streamWriter = new StreamWriter (fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin .End);
m_streamWriter.WriteLine( " *************************** \n" );
m_streamWriter.WriteLine( " mcWindowsService: Service Stopped \n" );
m_streamWriter.WriteLine( " *************************** \n" );
m_streamWriter.Flush();
m_streamWriter.Close();
}
}
}

Output:
Note:- Thr program will write the content in the text file that we specified.
The following lines gets printed in the text file.

**************************
mcWindowsService: Service Started
**************************
***************************
mcWindowsService: Service Stopped
***************************
The term "web service" refers to a form of a component that can be used
remotely. Web services are invoked remotely using SOAP or HTTP-GET
and HTTP-POST protocols. Web services are based on XML and return an
"answer" to the client in XML format. Web services have all the advantages
of components plus many more.

The most significant benefits include:

1. Platform and Language Independence : Web services can be built


and consumed on any operating system just as long as that operating
system supports the SOAP protocol and XML.

2. Automatic Upgrade : Unlike components, if a web service requires an


update, that update is propagated to all applications consuming that
web service immediately. This is because the actual methods and
properties for the web service are invoked from the web server
remotely, meaning that each function contained within a web service
appears as a "black box" to a client: they aren't concerned with the
way the function does its job, just as long as it returns the expected
result.

Some Important Terms in Web Services:

1. UDDI : UDDI (Universal Description, Discovery and Integration) is a


registry that provides a place for a company to register its business
and the services that it offers. People or businesses that need a service
can use this registry to find a business that provides the service. When
you search for a web service using UDDI's web service or web
browser, UDDI returns a listing of web services that matched your
criteria. This list is returned in the form of a DISCO or WSDL
document.
2. WSDL: WSDL (Web Services Description Language) is a language
that describes a web service. It contains information such as where
you can find the web service, methods and properties that it supports,
its data types, and the protocol used to communicate with the web
service. WSDL is based on the XML format and it's used to create
proxy objects. Basically, without a WSDL document, developers
wouldn't be able to use web services simply because they wouldn't
know which methods and properties they support and also which
communication method any particular web service supports.

3. DISCO : DISCO (Abbreviated from disco very) is a list of WSDL


documents. DISCO is used to group common web services together.
DISCO documents are also in XML format.
4. SOAP: SOAP (Simple Object Access Protocol) is a protocol to
transport data to and from the web server. It is in XML format and
allows you to transport a variety of data types used in .NET. As an
alternative to SOAP, we can use HTTP-GET and HTTP-POST, which
will be covered later in the article. These protocols return the output in
a non-SOAP format; however this output is still in XML format.

Example: Demonstrate Web Service

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[ WebService (Namespace = "http://tempuri.org/" , Description = "New


WEB Service Developed by V.D" )]
[ WebServiceBinding (ConformsTo = WsiProfiles .BasicProfile1_1)]
public class Service : System.Web.Services. WebService
{
public Service () {
//Uncomment the following line if using designed components

//InitializeComponent();
}
[ WebMethod (Description= "GetEmployeeName: This will return the
Employee Name." )]
public string getEmployeeName()
{
return "James Tube" ;
}
[ WebMethod (Description = "GetEmployeeAge: This will return the
Employee Age." )]
public string getEmployeeAge()
{
return "23" ;
}
}

Output: Run this Web Service or F5

Note:
1]. There are 2 methods that are associated with this web service.
2]. The web service us under the default namespace that is
http://tempuri.org. .
3]. Each XML Web service needs a unique namespace in order for client
applications to distinguish it from other services on the
Web.http://tempuri.org/ is available for XML Web services that are under
development, but published XML Web services should use a more permanent
namespace .

Output: If user clicks on the getEmployeeAge link

A Web Service is an external interface provided by a Web site that can be


called from other Web sites. For example, a financial company may make up
to the minute stock quotes available via Web Service for those who do their
trading with that company. This information could be read from a Web page
and displayed, or read from a stand-alone application on a customer's
desktop computer.

Client Communicate through web service:

SOAP over HTTP SOAP over HTTP

XML XML

Location 1
Location 2

Soap calls are remote function calls that invoke methods executions on Web
Service components at Location 2. The output is render as XML and pass
back to the Location 1 where the user wants to access the Web Service.
At Location 1, the user need to consume some of the functions of the web
service that is available on the internet, to make the remote function calls
(RFC). All the processing can't be done on the remote machine, therefore,
we have to create the proxy of the web service from where we can process
our data. This whole process is also called as marshalling of data.
Due to security threats, we create the proxy of the server object here it is
web service. That means we are creating a " proxy object " to act on behalf
of the original Web service. The proxy object will have all the public
available data interfaces as the original Web service.

Consuming a Web Service


The following are the steps to call/consume a webservice.

Step 1: Create a Web Service project and run it so that no compilation error
exists.

Step 2: Create new Web Site that will consume this web site that is there in
your system using the VS.Net. Create New Web Site with the name: Web
Site Name that will consume web service: WebService_Consume.
Step 3: Once you are done with the creation of the new site that will
consume the web Service. Let example the web service run as this URL:
http://localhost:1508/WebService_New/MyWebService.asmx

Step 4: Right click on the solution, Click on Add Web Reference. This
will open up a new pop-up window where you can specify the URL name of
your web service .

Here we specify the web service URL and if you look at the right panel there
is Web Reference Name: localhost [This the default name that is there].

Step5: We specify localhost_myWebService name for the web reference.


This will include 3 files under this folder.

MyWebService.disco

MyWebService.discomap

MyWebService.wsdl

Step6: Look Inside the contents of the disco file

<?xml version="1.0" encoding="utf-8" ?>


<discovery xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.xmlsoap.org/disco/">
<contractRef
ref="http://localhost:1508/WebService_New/MyWebService.asmx?wsdl"
docRef="http://localhost:1508/WebService_New/MyWebService.asmx"
xmlns="http://schemas.xmlsoap.org/disco/scl/" />
<soap
address="http://localhost:1508/WebService_New/MyWebService.asmx"
xmlns:q1="http://tempuri.org/" binding="q1:ServiceSoap"
xmlns="http://schemas.xmlsoap.org/disco/soap/" />
<soap
address="http://localhost:1508/WebService_New/MyWebService.asmx"
xmlns:q2="http://tempuri.org/" binding="q2:ServiceSoap12"
xmlns="http://schemas.xmlsoap.org/disco/soap/" />
</discovery>

Step7: Look Inside the contents of the discomap file

<?xml version="1.0" encoding="utf-8" ?>


<DiscoveryClientResultsFile
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Results>
<DiscoveryClientResult
referenceType="System.Web.Services.Discovery.DiscoveryDocumentRefere
nce" url="http://localhost:1508/WebService_New/MyWebService.asmx?
disco" filename="MyWebService.disco" />
<DiscoveryClientResult
referenceType="System.Web.Services.Discovery.ContractReference"
url="http://localhost:1508/WebService_New/MyWebService.asmx?wsdl"
filename="MyWebService.wsdl" />
</Results>
</DiscoveryClientResultsFile>

Example: Demonstrate the Consumption of the Web Service in the Web


Site

using System;
using System.Data;
using System.Configuration;
using System.Web;

using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI. Page


{
protected void Page_Load( object sender, EventArgs e)
{
}
protected void Button1_Click( object sender, EventArgs e)
{ //Consuming the WebServices through Add Web Reference
//Fetching the Value from the Web Services
localhost_myWebService. Service objServiceConsume = new
localhost_myWebService. Service ();
txtName.Text = objServiceConsume.getEmployeeName();
txtAge.Text = objServiceConsume.getEmployeeAge();
}
}

Output:

Click on the Fetcher button: This will fetch the value from the Web
Service.
There are many ways to consume Web Services.
1. The first way is to use a SOAP Proxy Client Object generated by the
WSDL utility, and it provides programmers with their familiar object
model that they can use to call methods provided by the generated
Proxy Interface.
2. The second way is to use HTTP-POST and HTTP-GET protocols.
3. The third way is to use a SOAP standard Request message that parses
SOAP response messages with the help of the XMLHTTP COM
object that is installed by the Microsoft XML Parser.

WSDL: Web Services Description Language (WSDL) is an XML based


protocol for information exchange in decentralized and distributed
environments. A WSDL document defines services as collections of network
endpoints, or ports. A WSDL document uses the following elements in the
definition of network services:

Types a container for data type definitions using some type system
(such as XSD).

Message an abstract, typed definition of the data being


communicated.

Operation an abstract description of an action supported by the


service.

Port Type an abstract set of operations supported by one or more


endpoints.

Binding a concrete protocol and data format specification for a


particular port type.

Port a single endpoint defined as a combination of a binding and a


network address.

Service a collection of related endpoints.

Proxy Class: This proxy class serves as an intermediate between the


ASP.NET Web page and the Web service

Consuming Web Service object:

1. The Asp.Net page instantiates an instance of the proxy class. For e.g.
ProxyClassName objproxy = new ProxyClassName();
2. Once the object is instantiated, then with the help of proxy object, this
will make a call to the web service method. For e.g.
objproxy.WebMethodName(any Parameter that has to send);
3. The proxy class marshals the parameter list and makes an HTTP
request to the Web service sitting on Web Server 2.
4. The Web service unmarshals the incoming parameters, runs the
method, and marshals the output parameters. These are sent back in an
HTTP response.
5. The proxy class unmarshals the return parameters and passes back the
result to the ASP.NET Web page.

Creating a Proxy Class:

Creating a Proxy class involves three steps:

Step 1:- First create the proxy class of the web service using the WSDL tool.
wsdl.exe:-Utility to generate code for xml web service clients and xml web
services using ASP.NET from WSDL contract files, XSD schemas and
discomap discovery documents. This tool can be used in conjunction with
disco.exe.

Run this from the Command Prompt:


C:\Program Files\Microsoft Visual Studio 8\VC> wsdl
http://localhost:1508/WebService_New/MyWebService.asmx
Microsoft (R) Web Services Description Language Utility
[Microsoft (R) .NET Framework, Version 2.0.50727.42]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'C:\Program Files\Microsoft Visual Studio
8\VC\Service.cs'.

Step 2:- This will create the Service.cs file on the specified location. After
this compile this Proxy Class to generate the compiled proxy
Class i.e. Service.dll Run this from the command Prompt:

C:\Program Files\Microsoft Visual Studio 8\VC> csc /t:library Service.cs


Microsoft (R) Visual C# 2005 Compiler version 8.00.50727.42
for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727
Copyright (C) Microsoft Corporation 2001-2005. All rights Reserved.

Step 3:-Place this compiled proxy class in the dll of the Web Site from
where you want to access the Web Service.

WSDL.EXE:
Wsdl.exe contains only one required parameter, a URL or path to the
WSDL for the Web service. The following optional parameters can be
specified:
/language: language specifies what language the Proxy class should be
created in (vb/cs/js).
/protocol: protocol specifies the payload protocol to be used (SOAP,
HttpGet, HttpPost)
/namespace: namespace the namespace of the generated Proxy class.
/out: filename the filename of the Proxy class.

Proxy Class inclusion

1. Add the proxy class to the newly created Web Site


2. Go to Solution Explorer; right click on that solution click on Add
Reference. Below pop-up window appears

1. Clicking Ok will include the proxy class to the solution under Bin
folder.
2. Now we can use this proxy class and the methods that are there in the
web services.

Note: A proxy class is a class containing all of the methods and objects
exposed by the Web service. These methods handle the marshalling of the

parameters into SOAP, sending the SOAP request over HTTP, receiving the
response from the Web service, and unmarshalling the return value. The
proxy class allows the client program to call a Web service as if the Web
service was a local component.
Once you create a proxy class using the .NET command-line tool wsdl.exe ,
a Web service client may invoke proxy class methods, which communicate
with a Web service over the network by processing the SOAP messages sent
to and from the Web service.

Example: Demonstrate the Creation of Proxy Class and its Usage

using System;

using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI. Page


{
protected void Page_Load( object sender, EventArgs e)
{

}
protected void btnCustomer_Click( object sender, EventArgs e)
{ //Fetching the Customer Data from the Proxy Class.
try
{
Service objService = new Service ();

txtCustomerAge.Text = objService.getEmployeeAge();
txtCustomerName.Text = objService.getEmployeeName();
}
catch ( Exception ex) {
Response.Write(ex.Source);
}
}
}

Output:

Click On the Customer Data Button:

Creating an XML document


<< Prev: Creating Proxy Object of Next: Reading XML document in C
Web Service
sharp >>
The .NET gives us flexibility to work with the XML files easily. .NET
provides following five namespaces for XML manipulation.
1. System.Xml:- Contains major XML classes.This namespace contains
many classes to read and write XML documents.Some classes under
this namespace are XmlReader, XmlTextReader,
XmlValidatingReader, XmlNodeReader, XmlWriter, and
XmlTextWriter.
2. System.Xml.Schema:- Contains classes which work with XML
schemas. XmlSchema, XmlSchemaAll, XmlSchemaXPath, and
XmlSchemaType are the classes comes under this namespace..

3. System.Xml.Serialization:- Contains classes that are used to serialize


objects into XML format documents or streams.
4. System.Xml.XPath:- Contains XPath related classes to use XPath
specifications. XPathDocument, XPathExression, XPathNavigator,
and XPathNodeIterator classes comes under this namespace..
5. System.Xml.Xsl :- Contains classes to work with XSLT
transformations.

Example: Demonstrate Creation of XML Document

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace _CSharpApplication
{
public partial class Form10 : Form
{
public Form10()
{
InitializeComponent();
}

private void button1_Click( object sender, EventArgs e)


{
XmlDocument xmldoc;
XmlNode xmlnode;
XmlElement xmlelem;
XmlElement xmlelem2;
XmlElement xmlelem3;
XmlText xmltext;

xmldoc= new XmlDocument ();


//XML DECLARATION SECTION

xmlnode=xmldoc.CreateNode( XmlNodeType .XmlDeclaration, "" , ""


);
xmldoc.AppendChild(xmlnode);
//STARTING NODE
xmlelem=xmldoc.CreateElement( "" ,txtRoot.Text, "" );
xmltext=xmldoc.CreateTextNode(txtRootDesc.Text);
xmlelem.AppendChild(xmltext);
xmldoc.AppendChild(xmlelem);
//ADD CHILD ELEMENT TO THIS NODE
xmlelem2=xmldoc.CreateElement( "" ,txtFirstChild.Text, "" );
xmltext=xmldoc.CreateTextNode(txtFirstChildDesc.Text);
xmlelem2.AppendChild(xmltext);
xmldoc.ChildNodes.Item(1).AppendChild(xmlelem2);
//ADD CHILD ELEMENT TO THIS NODE
xmlelem3 = xmldoc.CreateElement( "" ,txtSecondChild.Text, "" );
xmltext = xmldoc.CreateTextNode(txtSecondChildDesc.Text);
xmlelem3.AppendChild(xmltext);
xmldoc.ChildNodes.Item(1).AppendChild(xmlelem3);
//SAVE THE XML DOCUMENT IN A FILE
"C:\CREATEXML.XML"

try {
xmldoc.Save( "c:\\CREATEXMLDocument.xml" );
} catch ( Exception ex) {
Console.WriteLine(ex.Source);
}
MessageBox.Show( "***********XML DOCUMENT
CREATED************" );
}
}
}

Output:

Clicking on the Create XML Document after filling all the fields.

Generated XML files looks like:

<?xml version="1.0" ?>


<RootName>
<FirstChildName> FirstChildDesc </FirstChildName>
<SecondChildName> SecondChildDesc </SecondChildName>
</RootName>

Reading XML document in C sharp


<< Prev: Creating an XML
document

Next: Using XMLWriter class to


Write XML document in C sharp
>>

The XmlReader and XmlTextReader classes are defined in the


System.XML namespace.The XmlTextReader class is derived from
XmlReader class. The XmlTextReader class can be used to read the XML
documents. The read function of this document reads the document until
end of its nodes.

Example: The following example will show how the C# program will read
the xml file.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace _CSharpApplication
{
public partial class Form11 : Form
{
public Form11()
{
InitializeComponent();
}

private void button1_Click( object sender, EventArgs e)


{ //Read XML Document
try
{
// Open an XML file : Read Any XML that you have
XmlTextReader reader = new XmlTextReader
( "C:\\CREATEXMLDocument.xml" );
while (reader.Read())
{ // Move to first element
reader.MoveToElement();
lstReadXML.Items.Add( "XmlTextReader Properties Test" );
lstReadXML.Items.Add( "===================" );
// Read Element's Properties
lstReadXML.Items.Add( "Name:" + reader.Name);
lstReadXML.Items.Add( "Base URI:" + reader.BaseURI);
lstReadXML.Items.Add( "Local Name:" + reader.LocalName);
lstReadXML.Items.Add( "Attribute Count:" +
reader.AttributeCount.ToString());
lstReadXML.Items.Add( "Depth:" +reader.Depth.ToString());
lstReadXML.Items.Add( "Line Number:" +
reader.LineNumber.ToString());

lstReadXML.Items.Add( "Node Type:" +


reader.NodeType.ToString());
lstReadXML.Items.Add( "Attribute Count:" +
reader.Value.ToString());
}
}
catch ( Exception ex)
{
MessageBox .Show ( "Exception: {0}" , ex.ToString());
}

}
}
}

Output: The following screen will be displayed when run the above
program.

Clicking On the Read XML button the following screen will be


displayed.

Using XMLWriter class to Write XML document


in C sharp
<< Prev: Reading XML document
in C sharp

Next: Assembly Information :


Getting Permission set of the
assembly >>

The XmlWriter class contains the functionality to write to XML documents.


XmlWriter is an abstract base class and is a super class of XmlTextWriter
and XmlNodeWriter classes which are used to write the XML documents.
This class has many WriteXXX methods to write paired, unpaired and
empty XML elements. Some of these methods are used in a start and end
pair. For example, to write an element, you need to call WriteStartElement
then write a string followed by WriteEndElement.

Example: Demonstrate Writing to XML file

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace _CSharpApplication
{
public partial class Form12 : Form
{
public Form12()
{
InitializeComponent();
}

private void button1_Click( object sender, EventArgs e)


{ //Writing XML DOCUMENT

try
{
//CREATE NEW FILE
XmlTextWriter xmlWRITER = new XmlTextWriter
( "C:\\writeEmployeeRecordInXML1.xml" , null );
//OPEN DOCUMENT FOR WRITING
xmlWRITER.WriteStartDocument();

//WRITE COMMENTS
xmlWRITER.WriteComment( "Commentss: START DATE : 21OCT-07" );
xmlWRITER.WriteComment( "Commentss: WRITE XML
DOCUMENT" );
//WRITE FIRST ELEMENT
xmlWRITER.WriteStartElement( "EMPLOYEE" );
xmlWRITER.WriteStartElement( "r" , "RECORD" , "urn:record"
);
//WRITE NEXT ELEMENT
xmlWRITER.WriteStartElement( "EMPLOYEE NAME" , "" );
xmlWRITER.WriteString(txtName.Text);
xmlWRITER.WriteEndElement();
//WRITE ANOTHER ELEMENT
xmlWRITER.WriteStartElement( "EMPLOYEE ADDRESS" ,
"" );
xmlWRITER.WriteString(txtAddress.Text);
xmlWRITER.WriteEndElement();
//WRITE ANOTHER ELEMENT
xmlWRITER.WriteStartElement( "EMPLOYEE Date Of Birth" ,
"" );
xmlWRITER.WriteString(txtDOB.Text);

xmlWRITER.WriteEndElement();
//WRITE ANOTHER ELEMENT
xmlWRITER.WriteStartElement( "EMPLOYEE
Qualification" ,"" );
xmlWRITER.WriteString(txtQual.Text);
xmlWRITER.WriteEndElement();
//WRITE CHARACTERS
char [] ch = new char [3];
ch[0] = 'X' ;
ch[1] = 'M' ;
ch[2] = 'L' ;
xmlWRITER.WriteStartElement( "WRITING CHARACTER IN
XML DOCUMENT" );
xmlWRITER.WriteChars(ch, 0, ch.Length);
xmlWRITER.WriteEndElement();
// END OF DOCUMENT
xmlWRITER.WriteEndDocument();
// CLOSE WRITER
xmlWRITER.Close();
MessageBox.Show( "*********DONE***********" );

}
catch ( Exception ex) {
MessageBox .Show(ex.Source);
}

}
}}

Clicking on the Writing XML Document

This will generate a Xml file that contains the contents as given below:

writeEmployeeRecordInXML.xml
<?xml version="1.0"?>
<!--Commentss: START DATE : 21-OCT-07-->

<!--Commentss: WRITE XML DOCUMENT-->


<EMPLOYEE>
<r:RECORD xmlns:r="urn:record">
<EMPLOYEE NAME>Joseph</EMPLOYEE NAME>
<EMPLOYEE ADDRESS>Terry</EMPLOYEE ADDRESS>
<EMPLOYEE Date Of Birth>17-7-1981</EMPLOYEE Date Of Birth>
<EMPLOYEE Qualification>MBA</EMPLOYEE Qualification>
<WRITING CHARACTER IN XML DOCUMENT>XML</WRITING
CHARACTER IN XML DOCUMENT>
</r:RECORD>
</EMPLOYEE>

Assembly Information : Getting Permission set of


the assembly
<< Prev: Using XMLWriter class to
Write XML document in C sharp

Next: Creating your own Permission


Set >>

The basics of CAS is whenever any code is being executed in managed world
the .NET runtime verifies whether that code is allowed or not based on evidence
and set of permissions. Two important things that are very much importance to the
framework is:

Evidence:- From where the code comes? Is the code managed or


unmanaged.

Permissions:- The permission set on which the code executes.

Permissions and Permission Sets


Permission is what a code can do with particular resource like File, Registry etc.,
and Permission Set is collection of permission.

Policy Levels
NET System comes up with 4 Policies that are Enterprise , Machine User, and
AppDomain (which can be done through programmatically). Each policy has
multiple code groups and multiple permission sets.They have the hierarchy given
below.

Enterprise : All managed code in an enterprise setting.


Machine: All managed code on the computer.

User: Code in all processes associated with the current user.


Application Domain: Managed code in the host's application domain.

Example:- To get the permission set of Current Assembly.

Form13.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using System.Reflection;
using System.Security;
using System.Security.Policy;

using System.Security.Permissions;
using System.Collections;

namespace _CSharpApplication
{
public partial class Form13 : Form
{
//NAME OF THE BUILD_IN NAMED PERMISSION SET FOR FULLTRUST.
const string sFullTrust = "FullTrust" ;
static PermissionSet finalSet = new NamedPermissionSet
( "FinalAssemblySet" );
static PermissionSet permSet = null ;
//FIND OUT WHETHER THIS ASSEMBLY IS FULLTRUST PERMISSIONS.
static bool fullTrust = true ;
public Form13()
{
InitializeComponent();
}
private void Form13_Load( object sender, EventArgs e)
{

}
//FIGURE OUT THE CODEGROUP AND THE POLICY LEVEL OF THE
ASSEMBLY.
static bool isResGroups( CodeGroup _codeGroupparent, PolicyLevel
_policyLevel)
{
NamedPermissionSet _namedPermissionSet =
_policyLevel.GetNamedPermissionSet( _codeGroupparent.PermissionSetName);
if (isFullTrust(_namedPermissionSet)) return true ;
if (permSet == null ) permSet = ( PermissionSet )_namedPermissionSet;
else permSet = permSet.Union(_namedPermissionSet);
if (_codeGroupparent.Children.Count > 0)
{
foreach ( CodeGroup cp in _codeGroupparent.Children)
{
if (cp.Children.Count > 0)
isResGroups(cp, _policyLevel);
else
{
NamedPermissionSet nps2 =
_policyLevel.GetNamedPermissionSet( cp.PermissionSetName);
if (isFullTrust(nps2))

return true ;
permSet = permSet.Union(nps2);
}
}
}
//FULL TRUST CODE NOT FOUND
return false ;
}
//CHECK WHETHER THE PERMISSION SET IF FULLTRUST OR NOT FOR
THE CURRENT ASSEMBLY.
static bool isFullTrust( NamedPermissionSet _namedPermissionSet)
{
if (_namedPermissionSet.Name.Equals( "FullTrust" ))
return true ;
return false ;
}
//PASS THE PERMISSION SET AND LISTBOX AS ARGUMENT TO THE
FUNCTION.
static void getOutput( PermissionSet _permissionSet, ListBox _listBox)
{

IEnumerator psEnumerator = _permissionSet.GetEnumerator();


while (psEnumerator.MoveNext())
_listBox.Items.Add(psEnumerator.Current);
}
private void button1_Click( object sender, EventArgs e)
{ //Fetching the Permission Set of the Assembly
lstPermission.Items.Add( "List of permissions assign to current assembly" );
IEnumerator policy = SecurityManager .PolicyHierarchy();
while (policy.MoveNext())
{
PolicyLevel currentLevel = ( PolicyLevel )policy.Current;
CodeGroup group = currentLevel.ResolveMatchingCodeGroups ( Assembly
.GetExecutingAssembly().Evidence);
fullTrust &= isResGroups(group, currentLevel);
if (!fullTrust)
{
if (finalSet == null ) finalSet = permSet;
else finalSet = finalSet.Intersect(permSet);
permSet = null ;
}

else
{
lstPermission.Items.Add( "Current Level-" + currentLevel.Label + " || " +
"Group--" + group.Name + " || " + "Group Policy--" +
group.PermissionSetName);
}
}
if (fullTrust)
lblMode.Text = "Assembly is running in full-trust mode." ;
else
getOutput(finalSet, lstPermission);
}
}
}

Output:

Clicking on the Assembly Information button.

Creating your own Permission Set


<< Prev: Assembly Information :
Getting Permission set of the
assembly

Next: Using C sharp Socket >>

User can also create their own permission sets and code groups in the C#.
The following are the steps needs to follow to create your own permission
sets and code groups:-

Steps to create your own permission set and Code group

1. Go to Control Panel --> Administrative Tools --> Microsoft .NET


Framework 2.0 Configuration Double click on this a popup
windows appear

2. Creating a new Permission Set Expand Runtime Security Policy.


There are 3 security policy levels i.e. Enterprise , Machine and User. We are
creating the permission set for the machine security level.

3. Assign the permission to the permission set: Each permission set is a


collection of much different permission to various resources on the
computer. Select the permission that you need in the permission set.

4. Here I am selecting the File IO permission from the pool of permission


set. And then change the settings for this permission. Here specify the C:\
in the file path and assign only reading permission to this.

5. Here we assign 3 permission to the newly create permission set i.e. File
IO, Security and User Interface.

Create New Code Group


Create new code group and assign the permission that you create to this
code group so that your assembly will work under the specified permission

set. Right click on the All_Code node and this will open a pop-up window
i.e. Create Code Group wizard. Specify the name for your code group.

1. Choose a condition type for the code group:


The membership condition determines whether or not an assembly meets
specific requirements to get the permission associated with a code group.
Condition type in the specified context: Strong Name. You have to just
click on the Import button Select the assembly from the pop-up and this
will extract the information that we needed.

2. Assign a Permission Set to the code group:


Here through this window we can assign the permission set to this code
group that we are going to create. Select the permission set that we created
earlier. Though this window either we can create new permission set or
reuse the existing one.

3. Go through the properties of the newly created Code Group


Right click on the code group that you just created and you can view the
Code Group properties like the Code Group Name, its membership
conditions and permission set that is associated to it.

Create an Application: That will perform read and write operations on


file.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace winCreatingPSET
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click( object sender, EventArgs e)
{ //Writing to the Document
StreamWriter _streamWriter = new StreamWriter
( "c:\\TestPermission.txt" );
_streamWriter.WriteLine( " Security is Important" );
_streamWriter.WriteLine( " Security can provide Authentication " );
_streamWriter.Close();
}
private void button1_Click( object sender, EventArgs e)
{ //Reading from the Document
StreamReader _streamWriter = new StreamReader
( "c:\\TestPermission.txt" );

lstPSET.Items.Add(_streamWriter.ReadLine());
lstPSET.Items.Add(_streamWriter.ReadLine());
_streamWriter.Close();
}
}
}

Output:
Now run the application and try to click on the write button the screen,
this will give you following exception.:-

Using C sharp Socket

The System.Net.Sockets namespace contains the classes that provide the


actual .NET interface to the low-level Winsock APIs. This section gives a
brief overview of the C# Socket class. The core of the System.Net.Sockets
namespace is the Socket class. It provides the C# managed code
implementation of the Winsock API. The Socket class constructor is as
follows:
Socket(AddressFamily af , SocketType st , ProtocolType pt )
As you can see, the basic format of the Socket constructor mimics the
original Unix socket() function. It uses three parameters to define the type
of socket to create:

An AddressFamily to define the network type

A SocketType to define the type of data connection

A ProtocolType to define a specific network protocol

Each of these parameters is represented by a separate enumeration within


the System.Net_.Sockets namespace. Each enumeration contains the values
that can be used. For normal IP communications on networks, the
AddressFamily.InterNetwork value should always be used for the
AddressFamily. With the InterNetwork AddressFamily, the SocketType
parameter must match a particular ProtocolType parameter. You are not
allowed to mix and match SocketTypes and ProtocolTypes.

Socket Properties:
Several properties of the Socket class can be used to retrieve information
from a created Socket object

Property

AddressFamily

Description

Gets the address family of the Socket

Blocking

Gets or sets whether the Socket is in blocking


mode

LocalEndPoint

Gets the local EndPoint object for the Socket

Connected

Gets a value that indicates if the Socket is

connected to a remote device

RemoteEndPoint

SocketType

Handle

ProtocolType

Available

Gets the remote EndPoint information for the


Socket

Gets the type of the Socket

Gets the operating system handle for the Socket

Gets the protocol type of the Socket

Gets the amount of data that is ready to be read

Introduction to Socket Exceptions:

One feature of socket programming included in .NET Framework is neither


used by Unix nor the Winsock API is socket exceptions. All of the Socket
class methods use the SocketException exception. Any socket
programming you do should always check for SocketException exceptions
and then attempt to recover from the error, or at least warn the user of the
problem.

Example: Demonstrate Socket Properties and Socket Exception


Handling
using System;
using System.Collections.Generic;

using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace _CSharpApplication
{
public partial class Form5 : Form
{
public Form5()
{
InitializeComponent();
}

private void button1_Click( object sender, EventArgs e)

{ // Demonstrate Socket Properties


IPAddress _ipAddress = IPAddress .Parse( "127.0.0.1" );
IPEndPoint _ipEndPoint = new IPEndPoint (_ipAddress, 8000);
Socket _socketTest = new Socket ( AddressFamily .InterNetwork,
SocketType .Stream, ProtocolType .Tcp);
lstSocketProperties.Items.Add( "AddressFamily :: " +
_socketTest.AddressFamily);
lstSocketProperties.Items.Add( "SocketType :: " +
_socketTest.SocketType);
lstSocketProperties.Items.Add( "ProtocolType :: " +
_socketTest.ProtocolType);
lstSocketProperties.Items.Add( "Blocking :: "
+_socketTest.Blocking);
_socketTest.Blocking = false ;
lstSocketProperties.Items.Add( "new Blocking :: " +
_socketTest.Blocking);
lstSocketProperties.Items.Add( "Connected :: " +
_socketTest.Connected);
_socketTest.Bind(_ipEndPoint);
IPEndPoint _newIpEndPoint = ( IPEndPoint )
_socketTest.LocalEndPoint;
lstSocketProperties.Items.Add( "Local EndPoint :: " +
_newIpEndPoint.ToString());
_socketTest.Close();

private void button2_Click( object sender, EventArgs e)


{ //Socket Exceptions
IPAddress _hostIPAddress = IPAddress .Parse( "192.168.1.1" );
IPEndPoint _hostIPEndPoint = new IPEndPoint (_hostIPAddress,
8000);
Socket _socket = new Socket ( AddressFamily .InterNetwork,
SocketType .Stream, ProtocolType .Tcp);
try
{
_socket.Connect(_hostIPEndPoint);
}
catch ( SocketException e1)
{
lstSocketExceptions.Items.Add( "Problem Connecting To
Host ........" );
lstSocketExceptions.Items.Add(e1.ToString());
_socket.Close();
return ;
}

try
{
_socket.Send( Encoding .ASCII.GetBytes( "testing" ));
}
catch ( SocketException ex)
{
lstSocketExceptions.Items.Add( "Problem Sending Data" );
lstSocketExceptions.Items.Add(ex.ToString());
_socket.Close();
return ;
}
_socket.Close();
}
}
}