• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » C# » CSharp

Type of Array

By Dinesh Thakur

An array is a group or collection of similar type of elements.

 

An array is a group or collection of similar values. An array contains a number of variables, which are accessed through computed indexes. The various value contained in an array are also called the elements of array. All elements of an array have to be of same type, and this type is called the element type of the array. The element of an array can be of any type including an array type.

An array has a rank that determines the number of indexes associated with each array elements. The rank of an array is also referred as the dimension of the array. An array may be:

 

• Single Dimensional

• Multi Dimensional

An array with a rank of one is called single-dimensional array, and an array with a rank greater than one is called a multi dimensional array.

 

Each dimension of array has an associated length, which is an integer number greater than or equal to zero. For a dimension of length n, indices can range from 0 to n-l. In C#, array types are categorized under the reference types derived from. the abstract base. Types system. Array.

Single Dimensional Array

Single-dimensional arrays have a single dimension (ie. are of rank 1). The process of creation of arrays is basically divided into three steps:

 

1. Declaration of Array

2. Memory Allocation for Array

3. Initialization of Array

 

Declaration of Array

 

To declare an array in C# place a pair of square brackets after the variable type. The syntax is given below :

 

type[] arrayname;

For Example:

 

int [ ] a;

float[] marks;

double] x;

int [ ] m, n ;

You must note that we do not enter the size of the arrays in the declaration.

 

Memory Allocation for Array

 

After declaring an array, we need to allocate space and define the size. Declaring arrays merely says what kind of values the array will hold. It does not create them. Arrays in C# are objects, and you use the new keyword to create them. When you create an array, you must tell the compiler how many components will be stored in it. Here is given the syntax:

 

arrayname = new type[size];

 

For Example:

 

a = new int[5];

marks = new float[6];

x = new double[10];

m = int[100];

n = int [50];

It is also possible to combine the two steps, declaration and memory allocation of array, into one as shown below:

 

int[] num= new int [5];

 

Initialization of Array

 

This step involves placing data into the array. Arrays are automatically assigned the default values associated with their type. For example, if we have an array of numerical type, each element is set to number o. But explicit values can be assigned as and when desired.

Individual elements of an array are referenced by the array name and a number that represents their position in the array. The number you use to’ identify them are called subscripts or indexes into the array.

Subscripts are consecutive integers, beginning with 0. Thus the array “num” above has components num[0], num[l], num[2], num[3], and num[4].

The initialization process is done using the array subscripts as shown:

 

arrayname[subscript] = value;

 

For Example:

 

num[O] = 5;

num[1] = 15;

num[2] = 52;

num[3]·= 45;

num[4] = 157;

We can also initialize arrays automatically in the same way as the ordinary variables when they are declared, as shown below:

 

type[] arrayname = { list of values };

the list of variables separated by commas and defined on both ends by curly braces. You must note that no size is given in this syntax. The compiler space for all the elements specified in the list.

For Example:

 

int[] num = {5,15,S2,45,57};

You can combine all the steps, namely declaration, memory allocation and initialization of arrays like as: “,

 

int[] num = new int [5]” {5,15,52,4S,S7};

You-can also assign an array object to another. For Example

 

int [] a = { 10, 20, 30};

int [] b;

b=a;

The above example is valid in C#. Both the array will have same values.

Demonstration of array

using system;

class Number

{

public static void Main()

{

int [] num = {10, 20, 30, 40, SO};

int n =. num.Length;

II Length is predefined attribute to access the size of array

console.write(” Elements of ,array are :”);

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

{

console.writeLlne(num[i]);

}

int sum =0;

for(int i=O; i<n; i++) {

sum = sum +.num[i]); }

Console.writeLine(” The sum of elements :”+sum);

}

OUTPUT:

Elements of array are:

10

20

30

40

50

 

The sum of elements :150

Note : If you do not initialize an array at the time of declaration, the array members are automatically initilized to the default initial value for the array type. Also, if you declare the array as a field of a type, it will be set to the default value null when you instantiate the type.

Multi Dimensional Array

C# supports two types of multidimensional arrays:

 

• Rectangular Array

• Jagged Array

 

Rectangular Arrays

 

A rectangular array is a single array with more than one dimension, with the dimensions’ sizes fixed the array’s declaration. The following code creates a 2 by 3 multi-dimensional array:

 

int[,] squareArray =new int[2,3];

As with single-dimensional arrays, rectangular· arrays can he filled at the time they are declared. For instance, the code

 

int[,] squareArray = {{l, 2, 3}, {4 , 5, 6}};

 

creates a 2 by 3 array with the given values . .It is, of course, important that the given values do fill out exactly a rectangular array.

The System.Array class includes a number of methods for determining the size and bounds of arrays. These include’ the methods GetUpperBound(int i) and GetLowerBound(int i), which return, ;respectively, the upper and lower subscripts of dimension i of the array (note that i is zero based, so the first array is actually array 0).

For instance, since the length of the second dimension of squareArray is 3, the expression

 

squareArray.GetLowerBound(l)

returns 0, and the expression

 

squareArray.GetupperBound(l)

returns 2, because lowerbound is 0 and upperbound is 2 for length 3.

System.Array also includes the method GetLength(int i), which returns the number of elements in the ith dimension (again, zero based) ..

The following piece of code loops through squareArray and writes out the value of its elements.

 

for(int i = 0; i < squareArray.GetLengthCO); i++)

for (int j = 0; j < squareArray.GetLengthCl); j++)

console.writeLine(squareArray[i,j]);

A foreach loop can also be used to access each of the elements of an array in turn, but using this construction one doesn’t have the same control over the order in which the elements are accessed.

 

Jagged Arrays

 

A jagged array is an array whose elements are arrays. The elements can be different dimensions and sizes.

Using jagged arrays, one can create multidimensional arrays with irregular dimensions. This flexibility derives from the fact that multidimensional arrays are implemented as arrays of arrays. The following piece of code demonstrates how one might declare an array made up of a group of 4 and a group of 6 elements:

 

int[][] jag = new int[2][];

jag[0] = new int [4];

jag[l] = new int [6];

 

The code reveals that each of jag[O] and jag[l] holds a reference to a single-dimensional int array. ‘To illustrate how one accesses the integer elements: the termjag[0] [1] provides access to the second element of the first group.

& Concept

To initialise a jagged array whilst assigning values to its elements, one can use code like the following:

 

int[ ][ ] jag = new int[ ][ ] {new int[ ] {1, 2, 3, 4}, new int[ ] {5, 6, 7, 8, 9, 10}};

 

Be careful using methods like GetLowerBound, GetUpperBound, GetLength, etc. with jagged arrays. Since jagged arrays are constructed out of single-dimensional arrays, they shouldn’t be treated as having multiple dimensions in the same way that rectangular arrays do.

 

To loop through all the elements of a jagged array one can use code .like the following:

 

for (int i = 0; i < jag.GetLength(O); i++)

for (int j = 0; j < jag[i].GetLength(O); j++)

console.writeLine(jag[i] [j]);

 

or

 

for (int i = 0; i < jag.Length; ‘i++)

for (int j = 0; j < jag[i].Length; j++)

console.writeLine(jag[i] [j]);

 

The following example builds on arrays myArray, whose elements are arrays. Each one of array elements has a different size.

 

using System;

public class Array Test

{

public static void Main()

{

II Declare the array of two elements

int [][] myArray = new int [2][];

II initilize the elements

myArray [0] = new int [5] {I, 3, 5, 7, 9};

myArray [1] = new int [4] {2, 4, 6, 8};

II Display the array elements

 

for (int i = 0; i< myArray.Length; i++)

{

console.write (“Element( {O}):”, i)

for (int j = 0; j < myArray [i].Length; j++)

console.write (“{O}”, myArray [i] [j]);

console.writeLine ();

}

}

}

 

OUTPUT:

 

Element (0): 1 3 5 7 9

Element (1): 2 4 6 8

Passing Arrays as Parameters

You can pass an initialized array to a method. Here we given example of a printArray (myArray); function for both single and multidimensional arrays.

Single Dimension

In following example, a string array is initialized and passed as a parameter to the printArray method, where its elements are displayed.

 

using System;

public class Arrayclass

{

static void PrintArray (string [] w)

{

for (int i = 0; i < w.Length; i++)

console.write (w[i]);

Console.writeline ();

}

public static void Main ()

{

II Declare and initialize an array

string [] weekDays = new string []

{“sun”, “Sat”, “Mon”, “Tue”, “wed”, “Thu”, “Fri”};

1/ Pass the array as a parameter

printArray (weekDays);

}

}

 

OUTPUT:

 

Sun Sat Mon Tue wed Thu Fri

Multi Dimension

In this example, a two dimensional array is initialized and passed to the PrintArray method, where its elements are displayed.

 

using system;

public class Arrayclass

{

static void printArray (int [,]w)

{

II Display the array elements

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

for (int j = 0; j < 2; j++)

console.writeLine (“Element {O}; {1} = {2}”, i, j,w[i ,j]);

}

public static void Main ()

{

II pass the array as a parameter

printArray (new int [,] {{1, 2}, {3, 4}, {5, 6}, {7, 8}});

}

}

OUTPUT:

 

Element (0, 0) =1

Element (0, 1) = 2

Element (1, 0) = 3

Element (1, 1) = 4

Element (2,    0) = 5

Element (2,   1) = 6

Element (3,    0) = 7

Element (3,   1) = 8

What is Scope of Variable

By Dinesh Thakur

In the body of a method, you can also declare variables that would be used internally. A variable declared in the body is referred to as a local variable. It cannot be accessed outside of the method it belongs to. After declaring a local variable, it is made available to the method and you can use it.

As mentioned with functions, C# doesn’t have the notion of global variables (in C/C++,

Visual Basic, Pascal, etc, a global variable is one that is declared outside of any class; such a variable is made available to any function, or even file, of the same program without being declared again where needed). Still, if you want to use the same variable in various methods of the main class, you can declare it outside of any method. The variable must be declared as static. That is, you must type the static keyword to its left when declaring it. Here is an example:

 

Using System;

Class Exercise

{

Static double Length;

Static void welcome()

{

console. WriteLine (“welcome to the wonderful world of c#”);

}

Static void Main ()

{

Welcome();

console. WriteLine ();

}

}

After declaring such a variable, you can access from any method that belongs to the same class. Here is an example, to understand the concept of static variable.

Use of static variable

 

using System;

class Cylinder

{

static double Length;

static double Width;

static double Area;

static double Get The Length ()

{

double Len;

console. Write (“Length: “);

Len= double. Parse (console. Read Line ());

return 1en;

}

static double GetThewidth()

{

 

double w;

console. Write \(“width: “);

w = double. Parse (console. Read Line ());

return w;

}

static void AreaRect ()

{

console. WriteLine (“Enter the Length and width of Rectangle “);

width = Get The width();

Length = Get The Length();

Area = Length * width;

}

static void show Area()

{

console. Write Line(“\n characteristics of Rectangle”);

console. write Line(“Length: “+ Length);

console. Write Line(“width :”+ width);

Console. Write Line(“Area :”+ Area); }

}

static void Main()

{

AreaRect ();

Show Area() ;

console. Write Line (); }

}

 }

 

OUTPUT:

 

Enter the Length and Width of Rectangle

Length: 38.24

Width: 32.58

Characteristics of Rectangle

Length: 38.24

Width: 32.58

Area : 1245.85

Type of Method in C#

By Dinesh Thakur

The Function defined with in class is called method. It is a code designed to work on the member data of class.

 

Methods are operations associated with types. To provide a type with methods is to give it some useful functionality. Often this functionality is made generally available, so that it can be utilized by other types.

A method declaration, specified within a class declaration, comprises a method-head and a method-body. The method-head is made up of the following elements (square brackets enclose those which are optional).

 

[attributes] [method-modifiers] return-type method-name ([formal-parameter-list])

 

An example of a method’s name would be Welcome. To distinguish a method from a variable, it is always followed by parentheses, sometimes empty. Since a method is used to perform an assignment, its job is included between an opening curly bracket “{“and a closing curly bracket “}”.Here is an example:

 

using system;

class Exercise

{

Welcome() { }

static void Main()

{

Console.writeLine();

}

}

 

If the assignment performed by a method is long, you can use many lines to define its behavior. For this reason, each bracket can be typed on its own line.

Any time you create a method, the compiler needs to know the type of value that the method would return. The type of value that a method would return is specified on the left side of the method’s name.

Some, even many; of the methods used in your programs will not return a value after they have performed an assignment. When a method doesn’t return a value, it is considered void. The return type of such a method is the void keyword. Here is an example:

 

using System;

class Exercise

{

void welcome()

{

}

static void Main()

{

console.writeLine();

}

}

 

Static Methods

Unlike some other languages like C/C++, Pascal, Visual Basic, etc, but like Java, C# doesn’t have the notion of global function: every method must belong to a class. For this reason, every program uses at least one class and we call this primary class, the main class. Because of this feature of the language, it imposes some rules on the way methods can be called. If you create a method in the main class of your project, you should indicate that the method will always belong to this main class. The method must be created as static.

To define a method as static, type the static keyword to its left. Here is an example:

 

using system;

Class Exercise

{

Static void welcome ()

{

}

Static void Main ()

{

Console.WriteLine ();

}

}

 

As we have used the Main () function so far, the behavior of a method is defined between its delimiting curly brackets. The section inside the curly brackets is called the body of a method. In the body of the method, you can simply display a sentence. Here is an example:

 

Using system;

Class Exercise

{

Static void welcome ()

{

Console.WriteLine (“welcome to the wonderful world of c#”);

}

Static void Main ()

{

Console.WriteLine ();

}

}

 

In the same way, you can use a method to perform any other assignment. After creating a method, you can use it where needed. Using a method is also referred to as calling it. If you create a simple method like the above Welcome (), to call it, type its name followed by parentheses and ending with a semi-colon. Here is an example:

 

Using System;

Class Exercise

{

static void welcome()

{

Console.WriteLine (“welcome to the wonderful world of c#”);

}

static void Main()

{

Welcome ();

Console.WriteLine ();

}

}

 

Methods with return value

If a method has carried an assignment and must make its result available to other methods or other classes, the method must return a value and cannot be void. To declare a method that returns a value, provide its return type to the left of its name. Here is an example:

 

Using system;

Class Exercise

{

Static double operation ()

{

}

static void Main()

{

}

}

 

After a method has performed its assignment, it must clearly demonstrate that it is returning a value. To do this, you use the return keyword followed by the value that the method is returning. The value returned must be of the same type specified as the return type of the method. Here is an example:

 

using System;

class Exercise

{

Static double operation()

{

return 24.55;

}

static void Main()

{

}

}

 

A method can also return an expression; provided the expression produces a value that is conform to the return type. Here is an example:

 

using system;

class Exercise

{

static double operation()

{

return 24.55 * 4.16;

}

static void Main()

{

}

}

 

When a method returns a value, the compiler considers such a method as if it were a regular value. This means that you can use Console .Write () or Console.WriteLine () to display its value. To do this, simply type the name of the method and its parentheses in the Console.Write () of the Console.WriteLine () methods’ parentheses. Here is an example:

 

Using system;

Class Exercise

{

Static double operation ()

{

Return 24.55;

}

Static void Main ()

{

Console.WriteLine(operation());

}

}

Methods with Arguments

Like a variable, an argument is represented by its type of value. For example, one method may need a character while another would need a string. Yet another method may require a decimal number. This means that the method or class that calls a method is responsible for supplying the right value, even though a method may have an internal mechanism of checking the validity of such a value.

The value supplied to a method is typed in the parentheses of the method and it’s called an argument. In order to declare a method that takes an argument, you must specify its name and the argument between its parentheses. Because a method must specify the type of value it would need, the argument is represented by its data type and a name. If the method would not return a value, it can be declared as void.

Below examples which uses the arguments.

Call by value

When calling the methods that take one or more arguments, we made sure that we provided the needed argument. This is because an argument is always required and the calling function or class must provided a valid value when calling such a method.

 

Call by value method

 

Using System;

Class cylinder

{

static double GetTheRadius()

{

Double rad;

Do

{

Console. Write (“Radius: “);

Rad = double. Parse (console. Read Line ());

If (rad < 0)

Console. Write Line (“please enter a positive number”);

} while (rad < 0);

Return rad;

}

Static double GetTheHeight ()

{

Double h;

Do

{

Console.Write (“Height: “);

h = double.Parse (console. Read Line ());

if ( h < 0 )

Console. Write Line (“please enter a positive number”);

} while (h < 0);

Return h;

}

 

Static double calculateBaseArea (double rad)

{

Return rad * rad * Math.PI;

}

Static double calculateLateralArea (double rad, double hat;)

{

Return 2 * Math.PI * rad * hgt ;

}

static double calculateTotalArea(double rad, double hgt)

{

return 2 * Math. PI * rad * (hgt + rad);

}

static double calculatevolume(double rad, double hgt)

{

return Math. PI * rad * rad * hgt;

}

static void processcylinder()

{

double Radius;

double Height;

double BaseArea;

double LateralArea;

double TotalArea;

double volume;

Console.Writeline(“Enter the dimensions of the cylinder”);

Radius GetTheRadius();

Height = GetTheHeight();

BaseArea = calculateBaseArea(Radius);

LateralArea = calculateLateralArea(Radius, Height);

TotalArea = calculateTotalArea(Radius , Height);

volume = calculatevolume(Radius, Height);

Showcylinder(Radius, Height, BaseArea, LateralArea, TotalArea , volume); }

static void ShowCylinder(double rad, double hgt, double BArea,

double Lateral, double Total, double vol) {

console.writeLine(“\ncylinder characteristics”);

console.writeLine(“Radius: {O}”, rad);

console.writeLine(“Height: {O}”, hgt);

console.writeLine(“Base: {O:F}”, BArea);

console.writeLine(“Lateral: {O:F}”, Lateral);

console.writeLine(“Total: {O:F}”,total);

console.writeLine(“volume: {O:F}”, vol);

}

static void Main()

{

processCylinder();

console.writeLine();

}

}

 

OUTPUT:

 

Enter the dimensions of the cylinder

Radius: 38.26

Height: 28.48

Cylinder Characteristics

Radius: 38.26

Height: 28.48

Base: 4598.75

Lateral: 6846.44

Total: 16043.94

Volume: 130972.40

Call by reference

If you supply the argument using its name, the compiler only makes a copy of the argument’s value and gives it to the calling method. Although the calling method receives the argument’s value and can use in any way, it cannot (permanently) alter it. C# allows a calling method to modify the value of a passed argument if you find it necessary. If you want the calling method to modify the value of a supplied argument and return the modified value, you should pass the argument using its reference.

To pass an argument as a reference, when defining and when calling the method, precede the argument’s data type with the ref keyword. You can pass 0, one, or more arguments as reference in the program or pass all arguments as reference. The decision as to which argument(s) should be passed by value or by reference is based on whether or not you want the called method to modify the argument and permanently change its value.

Here are examples of passing some arguments by reference:

 

void Area(ref double Side);

 

II The argument is passed by reference

 

bool Decision(ref char Answer, int Age);

 

II One argument is passed by reference

 

Here is an example of call by reference :

 

Method call by reference

 

using system;

class swap

{

static void swapvalue(ref int a, ref int b)

{

int temp =. a;

a = b;

b = temp;

}

public static void Main()

{

int x =10, y = 20;

console.writeLine(” values of x and yare:”);

Console.writeLine(” x = ” + x);

Console.writeLine(” y= ” + y);

Swapvalue (ref x, ref y);

console.wrjteLine(“After swapping values are:”);

console.writeLine(” x “+ x);

console.writeLine(” y = ” + y);

}

}

 

OUTPUT:

 

values of x and y are

 

x = 10

Y = 20

 

After swapping values are:

 

x = 20

Y = 10

Special Parameters

C# provides two special types of parameters for functions which are given below:

 

• Output parameter

• Parameter array

 

Output Parameter

 

In addition to passing values by reference, there is an output parameter used to pass result back to the calling method. Using out keyword you can declare output parameter, which does not create a new storage location like reference parameters. When a formal parameter is declared as out, the corresponding actual parameter in the calling method must also be declared as out. For Example

 

Use of output parameter

 

using system;

class Outparameter {

static void Area_of_sqaure(int x, out int y)

 

{

y = x * x;

}

public static void Main()

{

int m;

Area_of_sqaure (3, out m);

console.writLine(“Area of square :”+m); }

 

OUTPUT:

 

Area of Square: 9

Parameter Array

This type of parameter is defined using params keyword and this is used to handle variable number of arguments in the method. For Example:

 

Use of Parameter Array

 

using System;

class ArrayParameter

{

static void Myfun( params int[] a)

{

console.writeLine(“Elements of array are:”)

foreach( int i in a)

console.writeLine(i);

}

public static void Main()

{

int [] x = { 10, 20, 30};

Myfun(x);

Myfun();

Myfun(45,67) ;

}

}

 

OUTPUT:

 

Elements of array are:

 

10

20

30

 

Elements of array are:

Elements of array are:

45

67

In the above example the Myfunc() call is equivalent to

 

Myfunc (new int [] { });

 

And Myfun (45, 67) call creates an int type array with two elements 10 and 20 and passes

the newly created array as the actual argument to the method, it is equivalent to

 

Myfun (new int [] {45, 67});

 

No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration. If two parameters are specified in the function the params should be in last.

We can also use object type as parameter arrays. For Example:

 

public static void Main() {

objArr ‘(10, 20, “xyz”);,

}

static void objarr ( params object [] x)

{

foreach(object i in x)

{

Console.write(i);

}

}

In the above example Objarr is passed for an array of object reference. The method call automatically builds an object array to holds the arguments, boxing value types as necessary.

Method Overloading

Multiple methods of same name with different arguments in a single program or class is called method overloading.

 

A typical program involves a great deal of names that represent variables and methods of various kinds. The compiler does not allow two variables to have the same name in the same function. Although two methods should have unique names in the same program, C# allows you to use the same name for different functions of the same program following certain rules. The ability to have various methods with the same name in the same ‘program is referred to as method overloading or function overloading. The most important rule about function overloading is to make sure that each one of these methods has a different number or different type (s) of arguments.

& Concept

We will illustrate method overloading through an example:

 

Method overloading

 

using System;

public class Newproject

{

// Rectangle

static double Area(double l, double w)

{

return 1 * w;

}

// circle, overload area method

Static double Area (double R)

{

Const double PI = 3.14159;

return R * R * PI;

}

static void Main()

{

double length, width;

double Radius;

 

console.writeLine(“Enter the sides of Rectangle”);

console.write(“Length: “);

Length = double.parse(console.ReadLine());

console.write(“width: “);

width = double.parse(console.ReadLine());

 

console.writeLine(“\n Area of Rectangle:”);

console.writeLine(Area(Length, width));

 

console.write(“\nEnter the radius: “);

Radius = double.parse(console.ReadLine());

Console.writeLine(“ Area of circle: “);

console.writeLine(Area(Radius));

 

console.writeLine();

}

}

 

OUTPUT:

 

Enter the sides of Rectangle

Length : 10.2

Width: 3.25

Area of Rectangle : 33.15

Enter the radius : 6.27

Area of, circle: 123.5050

Multiple Main() Functions in C#

By Dinesh Thakur

C# has a strong feature in which we can define more than one class with the Main method. Since Main is the entry point for the program execution, there are now more than one entry points. In fact, there should be only one entry point. Which will be resolved by specifying which Main is to be used to the compiler at the time of compilation as shown below:

 

csc filename.cs/main : class name

 

Where filename is the name of file where code is stored and classname is the name of class containing the Main which we would like to be the entry point. To understand the concept lets see an example.

 

Program with multiple Main Methods

using system;

class First {

public static void Main()

{

conso1e.writeLine(“This is First Class”); }

}

class second {

public static void Main() {

conso1e.writeLine(“This is second class”); }

}

c1ass Third {

public static void Main() {

conso1e.writeLine(“This 1S Third Class”); }

}

Compilation and Execution of Program

(suppose the name of file is multiple.cs)

c:\> csc/main : second mu1tiple.cs

c:\> multiple

 

This is second class

 

C:\>

C:\> csc/main : first multiple.cs

C:\>multiple

This is First class

Command Line Arguments

By Dinesh Thakur

Command line arguments are parameters supplied to the Main method at the time of invoking it for execution. To understand the concepts see the example given below:

Program of Command line argument to accept name from the command line and writes to the console. (Sample.cs)

using System;

class sample

{

public static void Main( string[ ] args)

{

console.write(“welcome to”);

console.write(” ” +args[0]);

console.write(” ” +args[l]);

}

}

Execution for this program

C:\ > Sample My Home

Output of Example

Welcome to My Home

In Previous examples, we have used the Main method with no parameters. Notice that in the above example how the Main is declared.

Main is declared with a parameters args. The parameter args is an array of strings. Any arguments provided in the command line at the time of execution, are passed to the array args as its elements. We can access the array elements by using a subscript like args[0],args[1] and so on.

Like as in the command line” C:\> Sample My Home”, args[O] and args[1] contains:

Args [0] <– My

args [1] <– Home

There fore the values will be display of these parameters in Console.Write() statement.

What is Namespace in C#

By Dinesh Thakur

When many people work in creating the same program, it could be difficult to keep track of the names of various classes. If more than one programmer creates a class with the same name in the same program, there would be conflict and the program would not work. The solution to avoid this situation is to delimit sections of code with names.

A names pace is a section of code that is identified by a specific name. The name could be anything such as somebody’s name, the name of the company’s department, or a city. To create a namespace, you start with the namespace keyword followed by the name of the section.

Like a class, the section that is part of a names pace starts with an opening curly bracket “{“and ends with a closing curly bracket “}”.Here is an example:

namespace Jason

{

}

 

Between the curly brackets, you can type anything that is part of the namespace. For example, you can create a class inside of a namespace. Here is an example:

namespace Jason

{

class Airport

{

}

}

 

Accessing members of Namespace

 

After creating the necessary items in a names pace, you can use the period operator (.) to access an item that is part of the namespace. To do this, in the desired location, type the name of the names pace, followed by a period, followed by the desired member of the namespace. Here is an example:

namespace Accounting

{

class Departure

{

}

}

class Mainclass

{

static void Main)

{

Accounting.Departure

}

}

Namespace Nesting

Imagine that you create a namespace called Accounting and many people from the Accounting department are asked to create their methods and objects only in the Accounting names pace and you may have asked the Accounting programmers not to create their methods and objects outside of the Accounting namespace. One thing you can do is to create other names paces inside of the existing namespace.

Creating a namespace inside of an existing namespace is referred to as nesting the namespace. The namespace inside of another namespace is nested.

To create a namespace inside of another, simply type it as you would create another namespace. Here is an example:

namespace Accounting

{

namespace Jason

{

}

}

 

In the example above, the Jason namespace is nested inside of the Accounting namespace.

After creating the needed namespaces, nested or not, you can create the necessary methods and objects inside of the desired namespace. To access anything that is included in a nested namespace, you use the period operator before calling a member of a namespace or before calling the next nested namespace. Here is an example:

namespace Accounting

{

class payroll

{

}

}

namespace Personnel

{

namespace EmployeesRecords

{

class Timesheet

{

}

}

 

namespace Benefits

{

class Medicallnsurance

{

}

}

}

class Mainclass

{

static void Main()

{

Accounting. payroll

personnel.Benefits.Medicallnsurance

personnel.EmployeesRecords.TimeSheet

}

}

 

A line of code such as Accounting.Payroll is called a statement. Every statement must be terminated with a semicolon. Therefore, this statement may be written as:

Accounting.Payroll;

The System Namespace

To make programming in C# a little easier, many classes have already been created and stored in various namespaces. Each namespace in C# is used to provide a specific set of classes. The most regularly used namespace in the C# language is called System. Inside of the System namespace is a class called Console. The Console class is used to display things on the console screen also called the DOS window.

The Console class contains assignments (called methods) to display information on the screen or to retrieve information from the user who types it in the DOS window. The method that is used to display text on the screen is called Write. To use the Write() method, inside of the parentheses, type the sentence between double-quotes. Here is an example:

class program

{

static void Main()

{

System.console.write(“The Wonderful world of c# programming”);

}

}

 

Besides the Write() method, the Console class also provides a method called WriteLine(). The difference is that, after displaying something on the screen, the Write() method keeps the caret (cursor) on the same line but WriteLine() transfers the caret the next line.

The using Keyword

We saw that, to call an object or a method that is part of a namespace, you must “qualify” that method or object using the period operator. Instead of using this approach, if you already know the name of a namespace that exists or has been created in another file, you can use a special keyword to indicate that you are using a names pace that is defined somewhere. This is done with the using keyword. To do this, on top of the file (preferably), type using followed by the name of the namespace.

With the using keyword, you can include as many external namespaces as necessary.

You can use ‘=’ operator with using key word to assign the alias name for the any namespace see an example

 

using X = System.console;

 

after this statement you can use alias ‘X’ in place of ‘System. Console’ like this:

x.writeLine (“Hello”)

x.writeLine (“HoWare you”);

or

X.ReadLi ne();

Types of Statements in C#

By Dinesh Thakur

Like C++ it contains three types of statements.

1. Simple Statements

2. Compound Statements

3. Control Statements

Simple Statements

A simple statement is any expression that terminates with a semicolon. For example

varl = var2 + var3;

var3 = varl++;

var3++;

Compound Statements:

Related statements can be grouped together in braces to form a compound statement or block. For example:

{

int i = 4;

Console.WriteLine (i);

i++;

}

Semantically, a block behave like a statement and can be used anywhere a single statement is allowed. There is no semicolon after the closing braces. Any variable declared in a block remain in scope up to the closing brace. Once the block is exited, the block variables cease to exist. Blocking improves readability of program code and can help make your program easier to control and debug.

Control Statements

Again control statements are divided into three statements

(a) Loop statements

(b) Jump statements

(c) Selection statements

 

(a) Loop Statements

C# provides a number of the common loop statements:

• while

• do-while

• for

• foreach

while loops

Syntax: while (expression) statement[s]

A ‘while’ loop executes a statement, or a block of statements wrapped in curly braces, repeatedly until the condition specified by the Boolean expression returns false. For instance, the following code.

int a =0;

While (a < 3) {

System.Console. WriteLine (a);

a++;

}

Produces the following output:

0

1

2

do-while loops

Syntax: do statement [s] while (expression)

 

A ‘do-while’ loop is just like a ‘while’ loop except that the condition is evaluated after the block of code specified in the ‘do’ clause has been run. So even where the condition is initially false, the block runs once. For instance, the following code outputs ‘4’:

Int a = 4;

do

{

System.Console. WriteLine (a);

a++;

} while (a < 3);

 

for loops

Syntax: for (statement1; expression; statement2) statement[s]3

The ‘for’ clause contains three part. Statementl is executed before the loop is entered.

The loop which is then executed corresponds to the following ‘while’ loop:

Statementl

 

while (expression) {statement[s]3; statement2}

 

‘for’ loops tend to be used when one needs to maintain an iterator value. Usually, as in the following example, the first statement initializes the iterator, the condition evaluates it against an end value, and the second statement changes the iterator value.

for (int a =0; a<5; a++)

{

system.console.writeLine(a);

}

foreach loops

syntax:foreach (variablel in variable2) statement[s]

 

The ‘foreach’ loop is used to iterate through the values contained by any object which implements the IEnumerable interface. When a ‘foreach’ loop runs, the given variablel is set in turn to each value exposed by the object named by variable2. As we have seen previously, such loops can be used to access array values. So, we could loop through the values of an array in the following way:

int[] a = new int[]{1,2,3};

foreach (int b in a)

system.console.writeLine(b);

 

The main drawback of ‘foreach’ loops is that each value extracted (held in the given example by the variable ‘b’) is read-only

(b) Jump Statements

The jump statements include

• break

• continue

• goto

• return

• throw

break

The following code gives an example – of how it could be used. The output of the loop is the numbers from. 0 to 4.

 

int a = 0;

while (true)

{

system.console.writeLine(a);

a++;

if (a == 5)

break;

}

Continue

The ‘continue’ statement can be placed in any loop structure. When it executes, it moves the program counter immediately to the next iteration of the loop. The following code example uses the ‘continue’ statement to count the number of values between 1 and 100 inclusive that are not multiples of seven. At the end of the loop the variable y holds the required value.

int y = 0;

for (int x=l; x<101; x++)

{

if ((x % 7) == 0)

continue;

y++;

}

 

Goto

 

The ‘goto’ statement is used to make a jump to a particular labeled part of the program code. It is also used in the ‘switch’ statement described below. We can use a’goto’ statement to construct a loop, as in the following example (but again, this usage is not recommended):

int a = 0;

start:

system.console.writeLine(a);

a++;

if (a < 5)

goto start;

(c) Selection Statements

C# offers two basic types of selection statement:

• if-else

• switch-default

if-else

‘if-else’ statements are used to run blocks of code conditionally upon a boolean expression evaluating to true. The ‘else’ clause, present in the following example, is optional.

if (a == 5)

system.console.writeLine(“A is 5”);

else

system.console.writeLine(“A is not 5”);

 

‘if’ statements can also be emulated by using the conditional operator. The conditional operator returns one of two values, depending upon the value of a boolean expression. To take a simple example,

int i = (myBoo1ean) ? 1 : 0;

 

The above code sets i to 1 if myBoolean is true, and sets i to 0 if myBoolean is false. The ‘if statement in the previous code example could therefore be written like this:

system.console.writeLine (a==5 ? “A is 5” “A is not 5”);

 

switch-default

‘switch’ statements provide a clean way of writing multiple if – else statements. In the following example, the variable whose value is in question is ‘a’. If ‘a’ equals 1, then the output is ‘a>0’; if a equals 2, then the output is ‘a> 1 and a>0’. Otherwise, it is reported that the variable is not set.

switch(a)

{

case 2:

Console.writeLine(“a>l and “);

goto case 1;

case 1:

console.writeLine(“a>0”);

break;

default:

console.writeLine(“a is not set”);

break;

}

Each case (where this is taken to include the ‘default’ case) will either have code specifying a conditional action, or no such code. Where a case does have such code, the code must (unless the case is the last one in the switch statement) end with one of the following statements:

break; .

goto case k; (where k is one of the cases specified)

goto default;

From the above it can be seen that C# ‘switch’ statements lack the default ‘fall through’ behavior found in C++ and Java. However, program control does fall through wherever a case fails to specify any action. The following example illustrates this point; the response “a>0”

is given when a is either 1 or 2.

switch(a)

{

case 1:

case 2:

Console.WriteLine(“a>0”);

break;

default:

Console.WriteLine(“a is not set”);

break;

}

A Simple C# Program

By Dinesh Thakur

Let’s begin in the traditional way, by looking at the code of a Hello World program.

1. using System;

2. public class HelloWorld

3. {

4. public static void Main()

5. {

6. II This is a single line comment

7. /* This is a

8. multiple

9. line comment */

10. Console.WriteLine(“Hello World! “);

11. }

12. }

• The first thing to note about C# is that it is case-sensitive. You will therefore get compiler errors if, for instance, you write ‘console’ rather than ‘Console’.

• The second thing to note is that every statement finishes with a semicolon (;) or else takes a code block within curly braces.

Explanation of Program

Line 1: using System;

We are using the System namespace. The point of this declaration is mostly to save ourselves time typing. Because the ‘Console’ object used in line 10 of the code actually belongs to the ‘System’ namespace, its fully qualified name is ‘System.Console’. However, because in line 1 we declare that the code is using the System namespace, we can then leave off the ‘System.’ part of its name within the code.

Line 2: public class HelloWorld

As C# is an object-oriented language, C# programs must be placed in classes. This line declares the class to be named ‘HelloWorld’.

 

Line 4: public static void Main()

 

When compiled and run, the program above will automatically run the ‘Main’ method declared and begun in this line. Note again C#’s case-sensitivity – the method is ‘Main’ rather than ‘main’.

Line 3, 11 and 5, 12:

These lines uses the ‘{‘for starting braces and ‘}’ for closing braces of block.

 

Lines 6-9: Comments

(‘//’ uses for single line and ‘/*…………. */’ uses for multiple line comments)

These lines of the program are ignored by the compiler, being comments entered by the programmer for his own benefit.

 

Line 6 shows a single line comment, in which everything on the line after the two forward slashes is ignored by the compiler.

 

Lines 7-9 demonstrate a multi-line comment, in which everything between the opening /*and closing */ is ignored, even when it spans multiple lines.

 

Line 10: Console.WriteLine (“Hello World”);

The statement on this line calls the ‘WriteLine’ method of the Console class in the System names pace. It should be obvious how this works in the given example – it just prints out the given string to the ‘Console’ (on PC machines this will be a DOS prompt).

Instruction for Saving the Program

In order to run the program, it must first be saved in a file. Unlike in Java, the name of the class and the name of the file in which it is saved do not need to match up, although it does make things easier if you use this convention. In addition, you are free to choose any extension for the file, but it is usual to use the extension ‘.cs’.

Writing program in Computer

There are two ways of program writing in computer

• Using Text Editor

• Using Visual Studio.NET

Using Text Editor:

We are giving the steps for writing the program in text editor, notepad.

 

1. Start Notepad

2. In the empty file, type the following

                          Using Text Editor

3. To save the file, on the main menu, click File -> Save

4. Select and display the C: (or the D 🙂 drive in the Save in combo/box

5. Click the Create New Folder button

6. Type Exercise! and press Enter twice or display the new folder in the Save In combo box

7. Save the file as exercise.cs using double quotes.

                          . Save the file as exercise.cs using double quotes

Using Visual Studio.NET

To create a console application using Visual Studio .NET follow the steps which are given below:

 

  1. Open Visual Studio .NET.

                          Open Visual Studio .NET

2. Create a new console application project by selecting the

File -> New -> Project ….. Menu item:

                     Menu item

3. Select the Visual C# Projects folder from Project types: Pane of the window that appears, and Console Application project type in the Template: pane.

                            Select the Visual C# Projects folder from Project types

4. Click the OK button. Once the project is initialized, add the code of program to file displayed in the main window:

                             Code main window

5. Save the application file by selecting the File I Save Class1.cs or press Ctrl +S.

                             Save the application file by selecting the File

Compilation and Execution

 

The compiler that ships with the C# version we will use, that is, the compiler of the .NET

Frameworks a program called csc. Like most other programs, it has the extension .exe. This csc name is not standard. This means that another C# compiler may have another name; csc.exe is just the name of the compiler we will use.

To use csc.exe, you should first find it in your computer. By default, it is installed in a

Folder like C:\ WINDOWS \ Microsoft.NET \ Framework. To use this compiler in all of your programs, you should include it in your system path.

After saving the file as ‘exercise.cs’.

To compile the program – open the Command Prompt and change to the folder in which

You created the C# file:

C:\ > cd Exercise l

C:\ Exercise l> csc exercise.cs

You Will see the following output on your screen in the dos box.

Microsoft (R) Visual C# Compiler Version 7.00.9254 [CLR version vl.0.29l4]

copyright (C) Microsoft Corp 2000-2001. All rights reserved.

Its means your program is successfully compiled. Other wise it will show the error, to remove go back to the program.

This command would generate the executable exercise.exe, which could be run in the usual way, by entering its name:

C:\Exercise1> exercise

Fairly obviously, this program would produce the output:

Hello World!

For Visual Studio Users:

  1. Compile the application by selecting Build | Build Solution or press Ctrl + Shift + B.

                                Compile the application by selecting Build

2.    To execute the application select Debug I Start without Debugging or press Ctrl + F5.

                                 To execute the application select Debug

Here is execution of the application. :

                                 execution of the application.

Different Ways of C# Program

The following examples show different ways of writing the C# Hello World Program.

Normal Program

public class Helloworld

{

public static void Main()

{

System.console.writeLine(“Hello world!”);

}

}

Output of Example

Hello World!

To avoid fully qualifying classes throughout a program, we can use the ‘using’ directive

Using system;

Public class Helloworld

{

public static void Main()

{

console.writeLine(“Hello world!”);

}

}

 

Output of Example

 

Hello World!

 

To return a return code, change the prototype of Main function

using system;

public class Helloworld

{

Console.writeLine(“Hello world!”) ;

return 0;

}

}

 

Output of Example

Hello World!

All of the above three examples will generate the same output. In first example we have used ‘System’ namespace with in the program. In the second example we have used ‘System’ namespace as directive with ‘using’ keyword. And in the third example we have used ‘Main’ function with return value.

Explain C# Data Type

By Dinesh Thakur

C# is a type-safe language Variables· are declared as .being of a particular type; and each variable is constrained to hold only values of its declared type.

Variables can hold either value types or reference types, or they can be pointers. Here’s a quick recap of the difference between value types and reference types.

• Where a variable v contains a value type, it directly contains an object with some value. No other variable v’ can directly contain the object contained by v (although v’ might contain an object with the same value).

• Where a variable v contains a reference type, what it directly contains is something which refers to an object. Another variable v’ can contain a reference to the same object referred to by v.

Value Types

C# defines the following value types:

  • Primitives int i;
  • Enum enum state {off, on }
  • Struct struct Point{ int x, y; }

It is possible in C# to define your own value types by declaring enumerations or structs.

These user-defined types are mostly treated in exactly the same way as C#’s predefined value types, although compilers are optimized for the latter.

The following table lists, and gives information about, the predefined value types. Because in C# all· of the apparently fundamental value types are in fact built up from the (actually fundamental) object type; the list also indicates which System types in the .NET framework correspond to these pre-defined types.

                .NET framework correspond to these pre-defined types.

 

                .NET framework correspond to these pre-defined types.

In the following lines of code, two variables are declared and set with integer values.

 

Int X = 10

Int y = x

      y   = 20; // after this statement x holds value 10 and y holds value 20

 

Reference Types

The pre-defined reference types are object and string, where object – is the ultimate base class of all other types. New reference types can be defined using ‘class’, ‘interface’, and ‘delegate’ declarations. There fore the reference types are:

Predefined Reference Types .

• Object

• String

User Defined Reference Types

• Classes                      • Interfaces

• Delegates                  • Arrays

Reference types actually hold the value of a memory address occupied by the object they reference. Consider the following piece of code, in which two variables are given a reference to the same object (for the sake of the example, this object is taken to contain the numeric property ‘myValue’).

 

class Demo

{

class XYZ

{

public int myvalue;

}

public static void Maine)

 

{

Xyz X= new Xyz();

x.myvalue 10;

XYZ Z = x;

z.myvalue 20; II after this statement both

                             II x.myvalue and z.myvalue equal 20

}

}

 

This code illustrates how changing a property of an object using a particular reference to it is reflected in all other references to it. Note, however, that although strings are reference types, they work rather more like value types. When one string is set to the value of another, for example:

 

string S1 = “hello”;

string S2 = S1;

 

Then s2 does at this point reference the same string object as s1. However, when the value of s1 is changed, for instance with

 

sl = “goodbye”;

 

What happens is that a new string object is created for s1 to point to. Hence, following this piece of code, s1 equals “goodbye”, whereas s2 still equals “hello”.

The reason for this behavior is that string objects are ‘immutable’. That is, the properties of these objects can’t themselves change. So in order to change what a string variable references, a new string object must be created.

Pointers

This section gives a brief overview of pointers and their use in C#. It only scratches the surface of a complicated topic, however, so if you are new to pointers .it is recommended that you do further reading before using them in your code. Luckily, pointers are only-really needed in C# where execution speed is highly important.

A pointer is a variable that holds the memory address of another type. In C#, pointers can only be declared to hold the memory addresses of value types (except in the case of arrays – see below).

Pointers are declared implicitly, using the ‘reference’ symbol *, as in the following example:

 

Int *p;

 

This variation appears to work just as well as the previous one.

This declaration sets up a pointer ‘p’, which will point to the initial memory address of an integer (stored in four bytes).

The combined syntactical element *p (‘p’ prefixed by the referencer symbol ‘*’) is used to refer to the type located at the memory location held by p. Hence given its declaration, *p can appear in integer assignments like the following:

*p=5

This code gives the value 5 to the· integer that was initialized by the declaration. It is important, however, not to confuse such an assignment with one in which the derefencer symbol is absent, e.g.

P=5;

The effect of this assignment is to change the memory location held by p. It doesn’t change the value of the integer initialized by the original declaration; it just means that p no longer points to that integer. In fact, p will now point to the start of the four bytes present at memory location 5.

Another important symbol for using pointers is the operator &, which in this context returns the memory address of the variable it prefixes. To give an example of this symbol, the following code sets up p to point to integer is memory location:

 

int i = 5 ;

int ‘*P

p = &i;

 

Given the above, the code

 

*P=10

 

Changes the value of i to 10, since ‘*p’ can be read as ‘the integer located at the memory value held by p’.

There is another important piece of notation for pointers. Pointers can be declared for structs, as in ·the following example (which uses the ‘Coords’ struct defined further below):

 

coords x = new coords();

coords *y = &x;

 

One can then use the declared pointer y to access a public field of x (say z). This would be done using either the expression

 

(*y).z

 

Or .the equivalent expression, which uses the -> string:

 

y -> z

 

Note that. Some programmers place the referencer symbol immediately after the type name, for example:

 

Boxing

Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value of a value allocated an object instance and copies the values into the new object.

Consider the following declaration of a value-type variable:

 

Int i = 123;

 

The following statement implicitly applies the boxing operation on the variables:

 

Object o = i;

 

The result of this statement is creating an object, on the stack, that references a value of the type int, on the heap. This value is a copy of the value-type value assigned to the variable i. The difference between the two variables, i and 0 is illustrated in the following figure.

                              Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type.

It also possible, but never needed to perform the boxing explicitly as in the following example

 

Int i = 123;

Object O = (object) i;

 

Unboxing

Unboxing is an explicit conversion from the object to value type or from an interface type to a value type that implements the interface. An unboxing operation consists of:

• Checking the object instance to make sure it is a boxed value of the given value type.

• Copying the value from the instance into the value-type variable.

The following statements demonstrate both boxing and unboxing operations:

 

Int i = 123;       // a value type

object O = i;   //boxing

int j = (int) O;   II unboxing

 

The following figure demonstrates the result of the preceding statements.

                            Unboxing is an explicit conversion from the object to value type or from an interface type to a value type that implements the interface.

For the unboxing of value types to succeed at runtime, the item being unboxed must be a reference to an object that was previously created by boxing an instance of that value type. Attempting to unbox null or a reference to an incompatible value type will return an invaIidcastException.

OPERATORS

C# has a number of standard operators, taken from C, C++ and Java. Most of these should be quite familiar to programmers; the less common ones are covered elsewhere.

The diagram below lists the standard operators. Note that when writing classes it is possible to change the default behavior of some of these operators (i.e. to ‘overload’ the operator), although this should only be done where the resultant semantics makes sense. The table indicates which of the operators are overloadable.

Primary Operators

 

 

C# KEYWORDS

By Dinesh Thakur

C# uses a series of words, called keywords, for its internal use. This means that you must avoid naming your objects using one of these keywords.

C# uses a series of words, called keywords, for its internal use.

Identifiers And Variables

By Dinesh Thakur

Identifiers refer to the names of variables, functions arrays, classes, etc. created by programmer. They are fundamental requirement of any language. Each language has its own rules for naming these identifiers.

To name the variables of your program, you must follow strict rules. In fact, everything else in your program must have a name.

There are some rules you must follow when naming your objects. On this site, here are the rules we will follow:

• The name must start with a letter or an underscore or the at symbol @.

• After the first letter or underscore, the name can have letters, digits, and/or underscores.

• The name must not have any special characters other than the underscore.

• The name cannot have a space.

• It should not a keyword.

C# is case-sensitive. This means that the names Case, case, and CASE are completely different. For example, the main function is always written Main.

FEATURES OF C#

By Dinesh Thakur

Simplicity

All the Syntax of java is like C++. There is no preprocessor and much larger library. C# code does not require header files. All code is written inline.

Consistent Behavior

C# introduced a unified type system which eliminates the problem of varying ranges of integer types. All types are treated as objects and developers can extend the type system simply and easily.

Modern Programming Language

C# supports number of modem features, such as:

• Automatic Garbage Collection

• Error handling features

• Modern debugging features

• Robust Security features

Pure Object-Oriented Programming Language

In C#, every thing is an object. There are no more global functions, variable and constants.

It supports all three object oriented features:

• Encapsulation

• Inheritance

• Polymorphism

Type Safety

Type safety promotes robust programming. Some examples of type safety are:

• All objects and arrays are initialized by zero dynamically

• An error message will be produced, on use of any uninitialized variable

• Automatic checking of array (out of bound and etc.)

Feature of Versioning

Making new versions of software module work with the existing applications is known as versioning. Its achieve by the keywords new and override.

Compatible with other Language

C# enforces the .NET common language specifications (CLS) and therefore allows interoperation with other .NET language.

Inter-operability

Language interoperability is the ability of code to interact with code that is written using a different programming language. Language interoperability can help maximize code reuse and, therefore, improve the efficiency of the development process.

C# provides support for using COM objects, no matter what language was used to author them. C# also supports a special feature that enables a program to call out any native API.

How to Comparing C# to C++ and Java

By Dinesh Thakur

Microsoft Corporation developed a new computer programming language C# pronounced as ‘C- Sharp’. C# is a simple, modem, object oriented, and type safe programming language derived from C and C++. C# is a purely object-oriented language like as Java. It has been designed to support the key features of .NET framework. Like Java, C# is a descendant language of C++ which is descendant of C language.

C# modernizes C++ by enhancing some of its features and adding a few new features. C# borrows Java’s features such as grouping of classes, interface and implementation together in one file so the programmers can easily edit the codes. C# also handles objects using reference, the same way as Java.

C# uses VB’s approach to form designing, namely, dragging controls from a tool box, dropping them onto forms, and writing events handlers for them.

Comparing C# to C++ and Java

C# versus Java

C# and Java are both new-generation languages descended from a line including C and C++. Each includes advanced features, like garbage collection, which remove some of the low level maintenance tasks from the programmer. In a lot of areas they are syntactically similar.

Both C# and Java compile initially to an intermediate language: C# to Microsoft Intermediate Language (MSIL), and Java to Java bytecode. In each case the intermediate language can be run – by interpretation or just-in-time compilation on an appropriate ‘virtual machine’. In C#, however, more support is given for the further compilation of the intermediate language code into native code.

C# contains more primitive data types than Java, and also allows more extension to the value types. For example, C# supports ‘enumerations’, type-safe value types which are limited to a defined set of constant variables, and ‘structs’, which are user-defined value types.

Unlike Java, C# has the useful feature that we can overload various operators.

Like Java, C# gives up on multiple class inheritance in favour of a single inheritance model extended by the multiple inheritances of interfaces. However, polymorphism is handled in a more complicated fashion; with derived class methods either ‘overriding’ or ‘hiding’ super class methods

C# also uses ‘delegates’-type-safe method pointers. These are used to implement event handling.

In Java, multi-dimensional arrays are implemented solely with single-dimensional arrays (Where arrays can be members of other arrays). In addition to jagged arrays, however, C# also implements genuine rectangular arrays.

C# versus C++

Although it has some elements derived from Visual Basic and Java, C++ is C#’s closest relative.

In an important change from C++, C# code does not require header files. All code is written inline.

As touched on above, the .NET runtime in which C# runs performs memory management, taking care of tasks like garbage collection. Because of this, the use of pointers in C# is much less important than in C++. Pointers can be used in C#, where the code is marked as ‘unsafe’, but they are only really useful in situations where performance gains are at an absolute premium.

Speaking generally, the ‘plumbing’ of C# types is different from that of C++ types, with all C# types being ultimately derived from the ‘object’ type. There are also specific differences in the way that certain common types can be used. For instance, C# arrays are bounds checked unlike in C++, and it is therefore not possible to write past the end of a C# array.

C# statements are quite similar to C++ statements. To note just one example of a difference: the ‘switch’ statement has been changed so that ‘fall-through’ behavior is disallowed.

As mentioned above, C# gives up on the idea of multiple class inheritance. Other differences relating to the use of classes are: there is support for class ‘properties’ of the kind found in Visual Basic, and class methods are called using the Operator rather than the :: operator.

What is Visual Studio .NET

By Dinesh Thakur

Many people always get confused with Visual Studio .NET (VS.NET) and .NET technology. VS.NET is just an editor, provided by Microsoft to help developers to write .NET programs easily. VS.NET editor automatically generates lot of code, allow developers to drag and drop controls to a form, provide short cuts to compile and build the application etc. [Read more…] about What is Visual Studio .NET

HOW CLR PROVIDES CROSS LANGUAGE INTERACTION

By Dinesh Thakur

A component can be called by any .NET-based language regardless the original language of that component. The cross-language compatibility is possible because objects created in different .NET languages agree on a common set of types and features. These common types and features are spelled out in the Common Language Specification (CLS).

Let’s take a look how CLR provide cross language interaction:

1. Every .NET based language compiler translates source language program into MSIL code.

2. The CLR also defines, the format’ of storing assembly metadata and this means all assemblies whatever language they were written in, share a common format for storing Metadata. ‘

3. All .NET based language follow Common Language Specification (CLS). CLS specifies a set of features that every .NET complaint language has to follow. A .NET complaint language may have its own unique features but it must follow the common set of features specified in CLS.

Because the target code of each .NET based compiler is represented in same language. The metadata is expressed in same language ‘and all sources language confirms to follow a set of features so the codes written in two different languages can interoperate.

 

Type of .NET Languages

By Dinesh Thakur

To help create languages for the .NET Framework, Microsoft created the Common Language Infrastructure specification (CLI). The CLI describes the features that each language must provide in order to use the .NET Framework and comm6n language runtime and to interoperate with components written in other languages. If a language implements the necessary functionality, it is said to be .NET-compliant.

Every .NET-compliant language supports the same data types, uses the same .NET Framework classes, compiles to the same MSIL, and uses a single common language runtime to manage execution. Because of this, every .NET-compliant language is a first-class Microsoft .NET citizen.-Developers are free to choose the best language for a particular component without losing any of the power and freedom of the platform. In addition, components written in one language can easily interoperate with components written in another language. For example, you can write a class in C# that inherits from a base class written in Visual Basic.

The .NET Framework was developed so that it could support a theoretically infinite number of development languages. Currently, more than 20 development languages work with the .NET Framework. C# is the programming language specifically designed for the .NET platform, but C++ and Visual Basic have also been upgraded to fully support the .NET framework. The following are the commonly used languages provided by the Microsoft:

• VC++

• VB.NET

.C#

• J#

• JScript .NET

Many third parties are writing compilers for other languages with .NET support. With CLR, Microsoft has adopted a much liberal policy. Microsoft has them selves evolved/ developed/ modified many of their programming languages which compliant with .NET CLR.

VC++

Although Visual C++ (VC++) , has undergone changes to incorporate .NET; yet VC++ also maintains its status being a platform dependent programming. Many new MFC classes have been added a programmer can choose between using MFC and compiling the program into a platform specific executable file; or using .NET framework classes and compile into platform independent MISL file. A programmer can also specify (via directives) when ever he uses “unsafe” (the code that by passes CLR, e.g. the use of pointers) code.

VB.NET

Out of ALL .NET languages, Visual Basic.NET (VB.NET) is one language that has probably undergone into the most of changes. Now VB.NET may be considered a complete Object- Oriented Language (as opposed to its previous “Half Object Based and Half Object Oriented” status).

Visual Basic .NET provides substantial language innovations over previous versions of visual basic. Visual Basic .NET supports inheritance, constructors, polymorphism, constructor overloading, structured exceptions, stricter type checking, free threading, and many other features. There is only one form of assignment: noLet of set methods. New rapid application development (BAD) features, such as XML Designer, Server Explorer, and Web Forms designer, are available in Visual Basic from Visual Studio .NET. With this release, Visual Basic Scripting Edition provides full Visual Basic functionality.

C#

Microsoft has also developed a brand new programming language C# (C Sharp). This language makes full use of .NET. It is a pure object oriented language. A Java programmer may find most aspects of this language which is identical to Java. If you are a new comer to Microsoft Technologies – this language is the easiest way to get on the .NET band wagon. While VC++ and VB enthusiast would stick to VC.NET and VB.NET; they would probably increase their productivity by switching to C#. C# is developed to make full use of all the intricacies of .NET. The learning curve of C# for a Java programmer is minimal. Microsoft has also come up with a The Microsoft Java Language Conversion Assistant-which is a tool that automatically converts existing Java-language source code into C# for developers who want to move their existing applications to the Microsoft .NET Framework.

J#

Microsoft has also developed J# (Java Sharp). C# is similar to Java, but it is not entirely’ identical. It is for this reason that Microsoft has developed J# – the syntax of J# is identical to Visual J++. Microsoft’s growing legal battle with Sun, over Visual J++ – forced Microsoft to discontinue Visual J++. So J# is Microsoft’s indirect continuation of Visual J++. It has been reported that porting a medium sized Visual J++ project, entirely to J# takes only a few days of effort.

JScript.NET

Jscript.NET is rewritten to be fully .NET aware. It includes support for classes, inheritance, types and compilation, and it provides improved performance and productivity features. JScript.NET is also integrated with visual Studio .NET. You can take advantage of any .NET Framework class in JScript .NET.

Third-party languages

Microsoft encourages third party vendors to make use of Visual Studio. Net. Third, party vendors can write compilers for different languages ~ that compile the language to MSIL

(Microsoft Intermediate Language). These vendors need not develop their own development environment. They can easily use Visual Studio.NET as an IDE for their .NET compliant language. A vendor has already produced COBOL.NET that integrates with Visual Studio.NET and compiles into MSIL. Theoretically it would then be possible to come up with Java compiler that compiles into MSIL, instead of Java Byte code; and uses CLR instead of JVM. However Microsoft has not pursued this due to possible legal action by Sun.

Several third party languages are supporting the .NET platform. These languages include APL, COBOL, Pascal, Eiffel, Haskell, ML, Oberon, Perl, Python, Scheme and Smalltalk.

User and Program Interface

By Dinesh Thakur

The .NET framework provides the following tools for manag1ng user and application interfaces:

 

• Windows forms

• Web Forms

• Console Applications

• Web Services

 

These tools enable users to develop user-friendly desktop-based as well as web-based applications using a wide variety of languages on the .NET platform.

Window Forms

Windows forms (also called Win Forms) ate used to create GUI-for Windows desktop applications. The idea of Win Form has been borrowed from Windows Foundation Classes (WFC) which was used for Visual J++. Win Form provide an integrated and unified way of developing -GUI. It has a rich variety of windows controls and user interface support.

Numerous classes and functions were used by programmers to handle GUT. MFC in VC++, direct API in C++ and VB Forms Engine in VB are just a few examples of different ways of handling GUI.

Simply Win Form is just another group of wrapper classes that deal specifically with GUI. Win Form classes encapsulate the Windows Graphical APIs. Now the programmers would not need to use the Windows Graphical APIs directly; and since Win Form has been made apart of .NET. Class Framework; all the programming languages would use the same Win Form classes. This would rid the programmers of the need to learn different· GUI classes/tools. Win Forms in the part of the namespace System Winforms.

With Win Forms we can make a single user interface, and use it in VC++, VB, C#. Using

Visual Studio. NET simply designs the GUI, by dragging the controls on a form (something that all VC++ and VB programmers are well familiar with). Now you can use the same form either in VB, VC++ or in C#. And this is all made possible because Visual Studio.NET uses the System. Winforms namespace to draw the GUI. And any language that has the appropriate CLS compliance can use this form directly.

Web Forms

Just as the Win Forms provide a unified way of developing GUI for desktop application, the Web Forms provide similar tool for web applications. Web Forms has been introduced in .NET as a part of ASP.NET. Web’ Forms are a form engine, that provides a browser-based user interface.

To appreciate Web Forms you may consider how GUI is rendered in current Web applications. The GUI is rendered by using HTML tags. (e.g. <input type=text name=editboxl maxlength=10 size=10 >, will draw an edit box on the web page) Web Forms can also have the intelligence to use HTML, DHTML, and WML etc. to draw the controls on the web page based on the browser’s capabilities. Web Forms can also incorporate the logic behind these controls. It’s like hooking up the code to a GUI control. Just like in your VB application, you can associate a code with a button on the web page; this code will be run on the server when the button is pressed. This is in contrast to the scripts that run on the clients when a button is pressed.

This approach is different to the Java approach. In Java a programmer can simulate this functionality through JavaScript and Servlets. But with Web forms this is done transparently.

A Java programmer may consider as if each HTML control has its dedicated “Servlets” running in the background. Every time the control receives any event of interest (e.g. button pressed, selection changed etc.) this specific “Servlets” is called. This results in much cleaner code and an excellent logic separation between presentation and business logic layers.

Web Forms consist of two parts – a template, which contains HTML-based layout information for all the GUI elements and a Component which contains all the logic to be hooked to the controls or GUI elements. This provides a neat presentation layer and application logic layer separation.

The GUI will be rendered on the client side, while the code that has been hooked to the GUI elements will run on the server side (very ‘much likes a button being pressed on a JSP and a Servlets being called in response. But with Win Forms this has been made extremely easy). The incorporation of Web Forms in ASP.NET is an attempt to take ASP to a new level where it can seriously challenge JSP.

Another good feature of Web Forms is that it can be built to have enough intelligence to support a vast variety of browsers. The same ASP page would render itself using DHTML, if the browser is IE 5.5. But if the browser is Netscape the web page will be rendered using HTML tags; if the’ page is being accessed through a WAP device the same page will render itself using WML tags.

One of the obvious disadvantages of ASP over Java was that there was that an ASP code was a maintenance nightmare. While a Java programmer can use Java Beans, Tags and also Servlets to achieve presentation and business layer separation – no such mechanism was present to an ASP programmer. With ASP.NET Microsoft ‘has provided such presentation business, layer separation – by introducing the concept of Web Forms:

1. ASP.NET Web Forms provide an easy and to build dynamic Web UI.

2. ASP.NET Web Forms pages can target any browser client (there are no script library or. cookie requirements).

3. ASP.NET Web Forms pages· provide syntax compatibility with existing ASP pages.

4. ASP.NET server controls provide an easy way to encapsulate common functionality.

5. ASP.NET ships with 45 built-in server controls. Developers can also use controls built by third parties.

6. ASP.NET templates provide an easy way to customize the look and feel of list server controls.

7. ASP.NET validation controls provide an easy way to do declarative client ·or server data validation.

Console Application

Console applications are command line oriented applications that allow user to read characters from the· console, write characters to the console.

Console applications are typically designed without graphical user interface and are compiled in a stand-alone executable file.

A console application is run from the command line with input and output information being exchanged between the command prompt and the running application. Because information can be written to and read from .the console window, this makes the console application a great way to learn new programming techniques without having to be concerned with the user interface.

Web Services

A web service is an extension of ActiveX. Those programmers, who have used ASP and JSP both, know the apparent shortcomings of ASP. JSP has been enriched with the concepts of Beans. And Tags. ASP equivalent for Beans and Tags was ActiveX Controls. and ActiveX automation servers. Let me take a minute to explain this point a bit further. Web Services is NOT a Microsoft proprietary standard. It is a W3Consortium standard, and has been developed by Microsoft, IBM and many other big names of the industry.

Functions are of two types. The ASP built-in functions and the programmer defined implemented functions. In order to use the built in functions you just need to pass the appropriate parameters and make a simple call to these functions. The functions are implemented by the ASP itself. The string manipulation functions, Number conversion functions are an, example of built in functions.

The user-defined functions are the functions that are defined and implemented by the programmer. A programmer can either write these functions in the same asp file or can write them in another file. If the function code resides in the same asp file then the programmer can directly call that function. In case the function resides in another file, say “func.asp”; then the programmer needs to include that file by writing a statement like <!- #include file=”func.asp” ->; and now the programmer can use the function. The programmers can also make ActiveX automation servers, and call various functions of these ActiveX servers, But one limitation is very obvious – no matter which type of function you use, the function MUST physically reside on the same machine. For example your ActiveX automation server must be implemented either as a .dll or as an .exe and then must also be registered in Windows Registry before an asp code can call its functions.

In a world where the Intemet has become not only a necessity but also a way of life – it is obvious that this limitation is a strong one; Microsoft’s answer to this problem is “Web Services”. The idea goes something like this:

1. The Web service provider develops a useful function(s), and publish/advertise it. The

Web Service provider uses Web Service Description Language (WSDL) standard to describe the interface of the function(s). This is much like the Type Libraries (TLB) and Object Description Language files (ODL) that needs to be generated with the ActiveX automation servers.

2. The programmer/client who needs the function does a lookup by using a process called

– Web Service Discovery or SOAP Discovery (also called DISCO for Web Service DISCOvery)

3. The Actual communication between the client program and the web service takes place through a protocol called Simple Object Access Protocol (SOAP) -SOAP is an XML based light weight protocol used for communication in a decentralized distributed environment.

UNIFIED CLASSES (Base Class Library)

By Dinesh Thakur

The term .NET framework refers to the group of technologies that form the development foundation for the Microsoft .NET platform. The key technologies in this group are the run time and the class libraries.

The Unified Classes (Base Class Library) is a set of classes that provide useful functionality to CLR programmers. The .NET Framework class library exposes features of the runtime and simplifies the development of .NET-based applications. In addition, developers can extend classes by creating their own libraries of classes. All applications (Web, Windows, and XML Web services) access the same .NET Framework class libraries, which are held in namespaces. All .NET-based languages also access the same libraries.

The run time is responsible for managing your code and providing services to it while it executes, playing a role similar to that of the Visual Basic 6.0 run time.

The .NET programming languages including Visual Basic .NET, Microsoft Visual C# and C++ managed extensions and many other programming languages from various vendors utilize .NET services and features through a common set of unified classes.

The .NET unified classes provide foundation of which you build your applications, regardless of the language you use. Whether you simply concating a string, or building a windows Services or a multiple-tier web-based applications, you will be using these unified classes.

The unified classes provide a consistent method of accessing the platforms functionality. Once you learn to use the class library, you’ll find that all tasks follow the same uniform architecture, you no longer need to learn and master different API architecture to write your applications.

By building your applications on a unified, integrated framework, you maximize your return on the time you spend learning this framework, and you end up with more robust applications that are easy to deploy and maintain.

Class Libraries

The .NET Framework has an extensive set of class libraries. This includes classes for:

• Data Access: High Performance data· access classes for connecting to SQL Server or any other OLEDB provider.

• XML Supports: Next generation XML support that goes far beyond the functionality of MSXML.

• Directory Services: Support for accessing Active directory/LDPA using ADSI.

• Regular Expression: Support for above and beyond that found in Perl 5.

• Queuing Supports: Provides a clean object-oriented set of classes for working with MSMQ.

These class libraries use the CLR base class libraries for common functionality.

Garbage Collection

By Dinesh Thakur

When you initialize a variable using the new operator, you are in fact asking the compiler to provide you some memory space in the heap memory. The compiler is said to “allocate” memory for your variable. When that variable is no longer needed, such as when your program closes, it (the variable) must be removed from memory and the space it was using can be made available to other variables or other programs. This is referred to as garbage collection. In the past, namely in C/C++, this was a concern for programmers because they usually had to remember to manually delete such a variable (a pointer) and free its memory.

The .NET Framework solves the problem of garbage collection by letting the compiler “clean” memory after you. This is done automatically when the compiler judges it necessary so that the programmer doesn’t need to worry about this issue.

Garbage collection is a mechanism that allows the computer to detect when an object can no longer is accessed. It then automatically releases the memory used by that object (as well as calling a clean-up routine, called a “finalizer,” which is written by the user). Some garbage collectors like the one used by .NET, compact memory and therefore decrease your program’s working set.

For most programmers, having a garbage collector (and using garbage collected objects) means that you never have to worry about deallocating memory, or reference counting objects, even if you use sophisticated .data .structures. It does require some changes in coding style, however, if you typically deallocate system resources (file handles, locks, and so forth) in the same block of code that releases the memory for an object. With a garbage collected object you should provide a method that releases the system resources deterministically (that is, under your program control) and let the garbage collector release the memory: when it compact the working set.

Just in Time Compiler(JIT)

By Dinesh Thakur

Machines cannot run MSIL directly. JIT compiler turns MSIL into native code, which is CPU specific code that runs on the same computer architecture as the JIT compiler. Because the common. Language runtime supplies a JIT compiler for each supported CPU architecture, developers can write a set of MSIL that can be JIT-compiled and run on computers with different architectures.

However, your managed code will run only on a specific operating system if it calls platform specific native APIs, or a platform-specific class library.

JIT compilation takes into account the fact that some code might never get called during execution. Rather than using time and memory to convert all the MSIL in a portable executable (PE) file to native code, it converts the MSIL as needed during execution and stores the resulting native code so that it is accessible for subsequent calls.

The loader creates and attaches a stub to each of a type’s methods when the type is loaded. On the initial call to the method, the stub passes control to the JIT compiler, which converts the MSIL for that method into native code and modifies the stub to direct execution· to the location of the native code. Subsequent calls of the JIT -compiled method proceed directly to the native code that was previously generated, reducing the time it takes to JIT-compile and run the code.

Managed and Unmanaged Code

Managed code is code that is written to target the services of the common language runtime. In order· to target these services, the code must provide a minimum level of information (metadata) to the runtime. All C#, Visual Basic .NET, and JScript .NET code is managed by default. Visual Studio .NET C++ code is not managed by default, but the compiler can produce managed code by specifying a command-line switch (/CLR).

Microsoft Intermediate Language (MSIL)

By Dinesh Thakur

A .NET programming language (C#, VB.NET, J# etc.) does not compile into executable code; instead it compiles into an intermediate code called Microsoft Intermediate Language (MSIL). As a programmer one need not worry about the syntax of MSIL – since our source code in automatically converted to MSIL. The MSIL code is then send to the CLR (Common Language Runtime) that converts the code to machine language which is then run on the host machine.

MSIL is similar to Java Byte code. A Java program is compiled into Java Byte code (the .class file) by a Java compiler, the class file is then sent to JVM which converts it into the host machine language.

Common Language Specification (CLS))

By Dinesh Thakur

One of the obvious themes of .NET is unification and interoperability between various programming languages. In order to achieve this; certain rules must be laid and all the languages must follow these rules. In other words we can not have languages running around creating their own extensions and their own fancy new data types. CLS is the collection of the rules and constraints that every language (that seeks to achieve .NET compatibility) must follow.

The Common Language Specification is a set of basic language features (constructs and constraints) that serves as a guide for library writers and compiler writers. It allows libraries to be fully usable from any language supporting the CLS, and for those languages to integrate with each other. The Common Language Specification is a subset of the common type system. The CLS is actually a set of restrictions on the CTS. The CLS defines not only the types allowed in external calls, but the rules for using them, depending on the goal of the user.

Informally CLS is a simply a contract between programming language designers and class library authors. The CLS is basically just a subset of the entire set of features supported by the CLR. The CLS includes things such as calling virtual methods, overloading methods and does not include things such as unsigned types. CLS is weighted very heavily in favor of the library designers.

The Common Language Specification describes a common level of language functionality. The CLS is a set of rules that a language compiler must adhere to in order to create .NET applications that run in the CLR. Anyone who wants to write a .NET·-compliant compiler needs simply to adhere to these rules and that’s it. The relatively high minimum bar of the CLS enables the creation of a club of CLS-compliant languages. Each member of this club enjoys dual benefits: complete access to .NET framework functionality and rich interoperability with other compliant languages. For example a VB class can inherit from a C# class and override its virtual methods.

The common language specification (CLS) is a collection of rules and restrictions that allow interoperation between languages. Even though the CLI does not require compilers to follow CLS, code that follows the CLS rules is compatible with all other languages that follow the CLS rules.

Microsoft has defined three level of CLS compatibility/compliance. The goals and objectives of each compliance level have been set aside. The three compliance levels with their brief description are given below:

Compliant producer

The component developed in this type of language can be used by any other language.

Consumer

The language in this category can use classes produced in any other language. In simple words this means that the language can instantiate classes developed in other language. This is similar to how COM components can be i:=1stantiated by your ASP code.

Extender

Languages in this category can not just use the classes as in CONSUMER category; but can also extend classes using inheritance.

Languages that come with Microsoft Visual Studio namely Visual C++, Visual Basic and

C#; all satisfy the above three categories. Vendors can select any of the above categories as the targeted compliance level(s) for their languages.

Common Type System (CTS)

By Dinesh Thakur

The language interoperability, and .NET Class Framework, are not possible without all the language sharing the same data types. What this means is that an “int” should mean the same in VB, VC++, C# and all other .NET compliant languages. Same idea follows for all the other data types. This is achieved through introduction of Common Type System (CTS).

Common type system (CTS) is an important part of the runtimes support for cross language integration. The common type system performs the following functions:

• Establishes a framework that enables cross-language integration, type safety, and high performance code execution.

• Provides an object-oriented model that supports the complete implementation of many programming languages.

The common type system supports two general categories of types:

1. Value types

Value types directly contain their data, and instances of value types are either allocated on the stack or allocated inline in a structure. Value types can be built-in, user-defined or enumerations types.

2. Reference types

Reference types stores a reference to the value’s memory address, and are allocated on the heap. Reference types can be self-describing types, pointers types, or interface types. The type of a reference type can be determined from values of self-describing types. Self-describing types are further split into arrays and class types are user-defined classes, boxed value types, and delegates.

                  Common type system (CTS) is an important part of the runtimes support for cross language integration.

CTS, much like Java, define every data type as a Class. Every .NET compliant language must stick to this definition. Since CTS defines every data type as a class; this means that only Object-Oriented (or Object-Based) languages can achieve .NET compliance. Given below is a list of most commonly used CTS supported data types:

                                CTS, much like Java, define every data type as a Class

Common Language Runtime (CLR)

By Dinesh Thakur

The Common Language Runtime (CLR) is a very important part of the .NET Framework. At the base level, it is the infrastructure that executes applications, and allows them to interact with the other parts of the Framework. It also provides important capabilities in optimizing, securing, and providing many robust capabilities such as application deployment and side-by-side execution.

The CLR provides a number of services that include:

• Code management (loading and execution)

• Application memory isolation

Verification of type safety

• Conversion of IL to native code

• Access to metadata (enhanced type information)

• Managing memory for managed objects

• Enforcement of code access security

• Exception handling, including cross-language exceptions

• Interoperation between managed code, COM objects, and pre-existing DLLs (unman aged code and· data)

• Automation of object layout

• Support for developer services (profiling, debugging, and so on)

 

The activity of CLR is shown in figure that goes on when application is executed. The source code is compiled to IL (also refer as MSIL) while the metadata engine creates metadata information. IL and metadata are linked with other native code if required and the resultant code is saved. During execution IL, the IL code and any requirement from the base class library are brought together by the class loader. The’ combined code is tested for type-safety and then compiled by the JIT compiler to produce native machine code, which is sent to the runtime manager (code manager) for code execution.

Components of CLR

Common Language Runtime (CLR) is a very important part of the .NET Framework.

The common language runtime simplifies application development, provider a robust and secure execution environment,

The common language runtime simplifies application development, provider a robust and secure execution environment, supports multiple language and simplifies application deployment and management. The environment is also referred to as a managed environment, one in which common services, such as garbage collection and security, are automatically provided. The common language runtime features are described in the following table:

Common Language Infrastructure (CLI)

By Dinesh Thakur

The Common Language Infrastructure (CLI) is an open specification developed by Microsoft that describes the executable code and runtime environment that allows multiple high-level languages to be used on different computer platforms without being rewritten for specific architectures. CLR is Microsoft Commercial implementation of Common Language Infrastructure (CLI).

The Common Language Infrastructure (CLI) is a theoretical model of a development platform that provides a device and language independent way to express data and behavior of applications.

                            Common Language Infrastructure (CLI) is an open specification developed by Microsoft that describes the executable code and runtime environment that allows multiple high-level languages to be used on different computer platforms without being rewritten for specific architectures

While the CLI primarily supports Object Oriented Programming (OOP) languages, procedural and functional languages are also supported. Through the CLI, languages can interoperate with each other and make use of a built-in garbage collector, security system, exception support, and a powerful framework.

What is Dot Net Framework

By Dinesh Thakur

Microsoft officially defined .NET Framework as follows:

 

The .NET Framework is the heart of Microsoft .NET. The .NET Framework is a software development platform of Microsoft .NET. Like any platform, it provides a runtime, defines functionality in some libraries, and supports a set of programming languages. The .NET Framework provides the necessary compile-time and run-time foundation to build and run .NET-based applications.

            The .NET Framework is the heart of Microsoft .NET

The .NET Framework consists of:

• Common Language Runtime

• Class Libraries

• Support for Multiple Programming Language

The common language runtime (CLR) (also refer as runtime). The Common Language

Runtime is the core of Microsoft’s .NET vision. This is said to be the execution engine of .NET platform. The runtime (CLR) handles runtime services, including language integration, security, and memory management. During development, the runtime (CLR) provides features that are needed to simplify development.

Class libraries: Class libraries provide reusable code for most common tasks, including data access, XML Web service development, and Web and Windows Forms. The CLR Software Development Kit (SDK) provides the programming APIs in the form of a set of classes for building .NET applications. Collectively, they are referred to the Base Class Library, or BCL.

Through the classes in the BCL, we can interact with the runtime, influencing the way that the runtime’s services are provided to us. In addition to giving us an “in” to the runtime, the BCL classes provide a large number of useful utilities. These include things like a new database access library (ADO.NET), ASP.NET, and an XML parser with support for the latest XML specifications. In addition, developers can extend classes by creating their own libraries of classes. All applications (Web, Windows, and XML Web services) access the same .NET Framework class libraries, which are held in namespaces.

Support for multiple programming languages. Having a set of libraries and a runtime is good, but neither one of them is useful if you can’t write programs to take advantage of them. In order to do that, you need to use some programming language with a compiler that is runtime-aware. Microsoft currently lists over twenty different languages with which it will be possible to write software that targets the CLR. Microsoft itself ship support for five languages with the SDK: C#, Visual Basic.NET, IL, C++, and JScript.NET. Of these, C# and Visual Basic.NET are likely to be the languages most often used to develop software for this new platform. Any language that conforms to the Common Language Specification (CLS) can run with the common language runtime. Relying on the common language runtime, code compiled with compilers of .NET based languages can interoperate. All .NET-based languages also access the same libraries.

Features of .NET Framework

• It is a platform neutral framework.

• It is a layer between the operating system and the programming language.

• It supports many programming languages, including VB.NET, C# etc.

• .NET provides a common set of class libraries, which can be accessed from any .NET based programming language. There will not be separate set of classes and libraries for each language. If you know anyone .NET language, you can write code in any .NET language.

 

• In future versions of Windows, .NET will be freely distributed as part of operating system and users will never have to install .NET separately.

Application Development and Execution

Developing application:

Since Microsoft .NET is a Multilanguage platform then any.NET based language can be chosen to develop applications. Comfort ability of application programmers, specific requirement of applications may be the major factors in selection of language.

Choosing a Compiler

According to the language we can choose its run time aware compiler for .NET platform. Because it is a Multilanguage execution environment, the runtime supports a wide variety of data types and language features.

Compiling to MSIL

When compiling your source code, the compiler translates it into an intermediate code represented in Microsoft intermediate language (MSIL). Before code Can be run, MSIL code must be converted to CPU-specific code, usually by a just-in-time (JIT) compiler. When a compiler produces MSIL, it also produces metadata. Metadata includes following information.

 

• Description of the types in your code, including the definition of each type,

• The signatures of each type’s members,

• The members that your code references,

• Other data that the runtime uses at execution time.

 

The MSIL and metadata are contained in a portable executable (PE) file that is based on and extends the published Microsoft PE and common object file format (COFF) used historically for executable content. This file format, which accommodates MSIL or native code as well as metadata, enables the operating system to recognize common language runtime images.

                         Compiling to MSIL

The presence of metadata in the file along with the MSIL enables your code to describe itself. This composite file serves as a self describing unit to the .NET Framework Runtime is called Assembly. The runtime locates and extracts the metadata from the file as needed during execution.

JIT Compilation to Native code:

The MSIL code is compiled into native code by component of CLR named JIT Compiler.

JIT compiler intelligently guesses and compiles the intermediate code on piece by piece basis. This piece may be a method or a set of methods. Before a method can be run, it must be compiled to processor-specific code. Each method for which Microsoft intermediate language (MSIL) has been generated is just-in-time-compiled (JIT-compiled) when it is called for the first time, and then run. The next time the method is run, the existing JIT -compiled native code is run. The process of JIT -compiling and then executing the code is repeated until execution is complete.

Type Safety Checking

As part of compiling MSIL to native code, code must pass a verification process unless an administrator has established a security policy that allows code to bypass verification. Verification examines MSIL and metadata to find out whether the code is type safe, which means that it only accesses the memory locations it is authorized to access. Additionally, verification inspects code to determine whether the MSIL has been correctly generated, because incorrect MSIL can lead to a violation of the type safety rules .

 

The runtime relies on the fact that the following statements are true for code that is verifiably type safe:

 

• A reference to a type is strictly compatible with the type being referenced.

• Only appropriately defined operations are invoked on an object.

• Identities are what they claim to be.

 

If type-safe code is required by security policy and the code does not pass verification, an exception is thrown when the code is run.

Code execution under CLR

The common language runtime is responsible for providing following low-level execution services, such as garbage collection, exception handling, security services, and runtime type safety checking. Because of the common language runtime’s role in managing execution, programs that target the .NET Framework are sometimes called “managed” applications.

 

What is Dot Net

By Dinesh Thakur

INTRODUCTION

The .NET is the technology from Microsoft, on which all other Microsoft technologies will be depending on in future. It is a major technology change, introduced by Microsoft, to catch the market from the SUN’s Java. Few years back, Microsoft had only VC++ and VB to compete with Java, but Java was catching the market very fast. With the world depending more and more on the Internet/ Web and java related tools becoming the best choice for the web applications, Microsoft seemed to be loosing the battle. Thousands of programmers moved to java from VC++ and VB. To recover the .market, .Microsoft announced .NET.

But Microsoft has a wonderful history of starting late but catching up quickly. This is true in case of .NET too. Microsoft put their best men at work for a secret project called Next Generation Windows Services (NGWS)., under the direct supervision of Mr. Bill Gates.

The outcome of the project is what we now know as .NET. Even though .NET has borrowed most of it’s ideas from Sun’s J2EE, it has really outperformed their competitors.

Microsoft’s VC++ was a powerful tool. But it was too complex. It has too many data types, and developers had to learn many libraries including Windows SDK, MFC, ATL, COM etc. There were many data type compatibility issues while exchanging data between different layers. Visual Basic was too easy, and many serious programmers hated it just for that reason. Even though Visual basic was very easy to use, it was not very flexible to develop serious applications. SUN’s Java became a very good choice for these reasons. It had the flexibility and power of C++ and at the same time easy enough to catch the attention of VB programmers.

Microsoft recognized these factors and they introduced the .NET considering all these factors. All unwanted complexities are eliminated and a pure object oriented programming model was introduced. This makes programmer’s life very easy.

.NET is said to be Microsoft development model in which software becomes platform and device independent and data becomes available over the internet. Due to this vision Microsoft .NET is also called Microsoft strategy for connecting systems, information and devices through web services so people can collaborate and communicates effectively.

The Microsoft .NET vision

The idea that all devices will some day be connected by a global broadband network

(Internet) and that software will become service provided over this network. “.NET” has been applied to everything from the next version of the Windows operating system to development tools.

Major Problems before .NET:

The following are the major problems in previous Microsoft Technologies faced by the developers for application development and deployment, which has been solved by the .NET:

Registration of COM components. COM components had to be registered on the target machine before they could be used by the application. The application had to look up the Windows registry to locate and load the COM components.

• Unloading COM components. COM objects also required a special logic for freeing up the objects from memory. This method is known as reference counting of COM objects. It is used to keep track of the number of active references. When an object’s reference count reaches zero, the object is removed from memory. The major problem that arises out of this situation is that of circular reference. If circular references exist between two COM components, they would not be freed from memory.

• Versioning Problem (DLL hell). Whenever applications that use COM components were installed on a machine, the installation process would update the registry with the COM components information. Thus, there was a chance that these DLLs would be overwritten when some other applications were installed on the same computer. Therefore, an application that had been referring to one particular DLL would refer to the wrong DLL. This caused a major problem when an application was referring to particular version of a DLL.

THE .NET PLATFORM

The .NET platform is a set of technologies. Microsoft .NET platform simplify software development (Windows or WEB) by building applications of XML Web services.

The.NET platform consists of the following core technologies:

• The .NET Framework

• The .NET Enterprise Servers

• Building block services

• Visual Studio .NET

                         The .NET is the technology from Microsoft, on which all other Microsoft technologies will be depending on in future.

A programming model (.NET Framework) that enables developers to build Extensible Markup Language (XML) Web services and applications.

A set of .NET Enterprise Servers, including Windows 2000, Microsoft SQL Server., and Microsoft BizTalk® Server, that integrate, run, operate, and manage XML Web services and applications.

The .NET Framework must run on an operating system. Currently, the .NET Framework is built to run on the Microsoft Win32® operating systems, such as’ Windows 2000, Windows XP, and Windows 98. When .NET Framework running on Windows 2000 then application services (such as Component Services, Message Queuing, Internet Information Services (IIS), and Windows Management Instrumentation (WMI) ) are available to the developers. The .NET Framework exposes application services through classes in the .NET Framework class library.

There are some client software such as Windows XP and Windows CE, which helps developers deliver a comprehensive user experience across a family of devices. A set of building block services that are a user-centric set of XML Web services that move control of user data from applications to users. For example, Microsoft Passport is a core component of the .NET initiative that makes it easier to integrate various applications.

XML Web services are programmable Web components that can be shared among applications on the Internet or the intranet. The .NET Framework provides tools and classes for building, testing, and distributing XML Web services.

Visual Studio .NET is a tool, which can be used to develop XML Web services and

Windows and Web applications for an enriched user experience.

« Previous Page

Primary Sidebar

C# Tutorials

C# Tutorials

  • C# - .NET Languages Types
  • C# - Dot Net
  • C# - Dot Net Framework
  • C# - Inheritance Types
  • C# - Features
  • C# - CTS
  • C# - CLS
  • C# - CLR
  • C# - Console
  • C# - MSIL
  • C# - Base Class Library
  • C# - Web Forms Creation
  • C# - C# Vs C++
  • C# - Statements Types
  • C# - JIT
  • C# - CLI
  • C# - Controls Types
  • C# - String Types
  • C# - Execution Model

Other Links

  • C# - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW