Tuesday, 14 February 2012

Structs,Enums and Arrays

Structs:

A struct provides a way to present a group of unlike variable types in a single name.it is very useful in creating user defined value types

Structs are nested in a namespace or class and it is a value type.

Syntax for declaring Structs is

(Modifiers) Struct structname

{

}

Example:

Public Struct sample

{

Public int I , j;

}

Class program

{

Public static void main (string []args)

{

Sample s=new sample ();

s.i=10;

s.j=20;

console.writeline (“ i = { 0 }, j ={ 1 }”, s.i , s.j );

}

}

Enums:

C# has the way to declare an enumerated data. This allows the programmer to provide a set of values for an instance of the group.

CLR automatically assigns each member of enumeration an integer value.

The first item is always assigned a zero followed by one.

Example:

Public enum week

{

Monday,

Tuesday,

Wednesday,

Thursday,

Friday,

Saturday,

Sunday

}

Class program

{

Public static void main (string [] args)

{

Week Today=week. Sunday;

Console.writeline (Today);

}

}

Arrays:

Array is a collection of similar data type that can be grouped by single name.

Array start with index number as zero followed by one. There are three type of arrays

· Single dimensional array

· Multidimensional array

· Jagged array

Single dimensional array:

If you want to declare elements in a single row, single dimensional array will be needed. In this there will be only one index for array members

Example:

int[] numbers = new int [5];

for ( int i=o;i< numbers. length; i++)

{

Numbers [i]= new int [4];

}

Multidimensional Arrays:

In C#, we can declare arrays by specifying the number of columns and number of rows by multidimensional arrays.

Jagged Arrays:

Some arrays contain an array of other arrays. These are called jagged arrays.

Example:

Class A

{

Static void main (string [] args)

{

String [] my array={“Hello “,”world”};

int [] myarray = new int[8];

int a,b;

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

{

myarray [i]=0;

}

int [][][] myarray2 =new int[3][][];//jagged array

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

myarray2[i] = new int[4][];

for (b=0;b<10;b++)

myarray2[a][b]= new int [5];

int [,] myarray =new int[5,5];//multidimensional array

for (int x=0,y=0;x<5;x++,y++)

{

myarray[x,y]=0;

}

}

}

No comments:

Post a Comment