You are on page 1of 77

ML1PCuS ln C#

synLax
modiIiers return-type method-name( Iormal parameter list )

method body// statements

Modlflers speclfy keywords LhaL declde Lhe naLure of


accesslblllLy and Lhe mode of Lhe appllcaLlon of Lhe
meLhod
Lxample
new publlc proLecLed lnLernal prlvaLe sLaLlc vlrLual
absLracL overrlde sealed exLern
MeLhods are exLremely useful because Lhey allow you Lo
separaLe your loglc lnLo dlfferenL unlLs ?ou can pass
lnformaLlon Lo meLhods have lL perform one or more
sLaLemenLs and reLrleve a reLurn value 1he capablllLy Lo
pass parameLers and reLurn values ls opLlonal and
depends on whaL you wanL Lhe meLhod Lo do
DLCLAkING ML1nCDS
$$nesLlng luncLlon
class nesLlng

publlc vold largesL(lnL m lnL n)

lnL largesL max(m n) $$nesLlng


ConsoleWrlLeLlne(largesL)
Console8eadkey()

lnL max(lnL a lnL b)

lnL x (a b) ? a b
reLurn x

class nesLLesL

publlc sLaLlc vold Maln()

nesLlng n new nesLlng()


nlargesL(13 14)

NLS1ING IUNC1ICN
INVCkING A ML1nCD
1he process of acLlvaLlng a meLhod ls known as
lnvoklng or calllng
ob[ectnamemethodname(actua| parameter ||st)
using System;
class nonstaticmethod

static void Main(string|| args)

Console.WriteLine("hello");
nonstaticmethod obj new nonstaticmethod();
double c obj.Cube(4);
Console.WriteLine('the cube is " c);
}
double Cube(Iloat x) //method is not static

return (x ` x ` x);
}
}
lf Lhe nonsLaLlc
meLhod ls deflned ln
Lhe same class Lhen
we call lL Lhrough Lhe
ob[ecL of Lhe class ln
Lhe maln meLhod
NCNS1A1IC ML1nCD IN SAML CLASS
using System;
class nonstaticmethod

static void Main(string|| args)

Console.WriteLine("hello");
nonstaticmethod obj new nonstaticmethod();
obj.Cube(4);
}
void Cube(Iloat x) //method is not static

double c(x * x * x);


Console.WriteLine('the cube is " c);
}
}
lf Lhe nonsLaLlc
meLhod ls deflned ln
Lhe same class Lhen
we call lL Lhrough Lhe
ob[ecL of Lhe class ln
Lhe maln meLhod
NCNS1A1IC ML1nCD IN SAML CLASS
using System;
class nonstaticmethod

8tatic void Main(string|| args)

Console.WriteLine("hello");
doub|e c Cube(4)
Console.WriteLine('the cube is " c);
}
8tatic double Cube(Iloat x)

return (x * x * x);
}
}
noLe
lf Lhe sLaLlc meLhod ls
deflned ln Lhe same
class Lhen we call lL
dlrecLly ln Lhe maln
S1A1IC ML1nCD IN SAML CLASS
uslng SysLem
class sLaLlcmeLhod

sLaLlc vold Maln(sLrlng args)


ConsoleWrlLeLlne(hello)
doub|e c x2Cube(3)
ConsoleWrlLeLlne(c)
Console8eadLlne()

class x2

publlc sLaLlc double Cube(floaL x)

reLurn (x * x * x)

noLe
lf Lhe sLaLlc meLhod ls
deflned ln Lhe
dlfferenL class Lhen
we call lL dlrecLly
uslng class name ln
Lhe maln of oLher
class
noLe
lf nonsLaLlc meLhod
ls Lhere ln dlfferenL
class Lhen Lhrough
ob[ecL we lnvoke lL
ln Lhe maln of oLher
class
NCNS1A1IC ML1nCD IN DIIILkLN1 CLASS
ML1nCD AkAML1LkS
1ypes of parameLers
Ialue parameLers
8eference arameLers
CuL puL parameLers
arameLer arrays
Va|ue parameters
lL allows a meLhod Lo asslgn values Lo Lhe value
parameLer Lhrough argumenLs glven ln a meLhod call
1hls Lype of asslgnmenL affecLs only Lhe local sLorage
locaLlon lL has no effecL on Lhe acLual argumenLs belng
asslgned ln Lhe meLhod call1he changes made Lo Lhe
parameLer are local Lo Lhe meLhod Lhey are noL passed
Lo Lhe calllng meLhod
Ialue parameLer are defaulL parameLers
lL ls also known as In parameLer
class passbyvalue

sLaLlc vold change(lnL m)

m m + 23
ConsoleWrlLeLlne(Lhe value of x lnslde funxLlonls + m)
Console8eadLlne()

publlc sLaLlc vold Maln()

lnL x 100
change(x)
ConsoleWrlLeLlne(Lhe value of x ls + x)
Console8eadLlne()

ASS 8 VALUL
keference arameter
8epresenLs Lhe same sLorage locaLlon lnsLead of creaLlng a new
sLorage locaLlon for Lhe varlable glven as Lhe argumenL ln Lhe meLhod
lnvocaLlon
A parameLer declared wlLh a ref modlfler ls a reference parameLer
Lxample
vold fun(ref lnL x)
xls reference parameLer
noLeWhen a formal parameLer ls declared as ref Lhe correspondlng
argumenL ln Lhe meLhod lnvocaLlon musL also be declared as ref
Lxample
vold fun(ref lnL x)
x+2 $$value of m wlll be changed
lnL n3 $$ lnlLlllzaLlon
fun(ref n) $$pass by reference
class passbyref

sLaLlc vold swap(ref lnL x ref lnL y)

lnL Lempx
xy
yLemp

publlc sLaLlc vold Maln()

lnL m 120 $$|n|t|a||zat|on |s necessary


lnL n 234
ConsoleWrlLeLlne(8efore swapplng)
ConsoleWrlLeLlne(m + m)
ConsoleWrlLeLlne(m + n)
Console8eadLlne()
swap(ref mref n)
ConsoleWrlLeLlne(AfLer swapplng)
ConsoleWrlLeLlne(m + m)
ConsoleWrlLeLlne(m + n)
Console8eadLlne()

ASS 8 kLILkLNCL
CU1U1 arameter
%hey are used to pass results back to the calling method.
Represents the same storage location
A parameter declared with an out modiIier is an output
parameter.
Every output parameter oI a method must be assigned beIore
the method returns the output.
%hey are typically used in methods that produce multiple
return values.
CU1U1 arameter
ote:When a Iormal parameter is declared as out the
corresponding actual argument in the calling method
invocation must also be declared as out.
Example
void Iun(out int x)
x100;}
...
int n; // no initialization
Iun(out n); //value oI n is set
$$output arguments
$*class ouLpuL

sLaLlc vold cube( ref lnL x ouL lnL y ouL lnL z) $$ meLhod deflnlLlon

y x * x
z x*x*x

publlc sLaLlc vold Maln()

lnL n 12
lnL mb
cube( ref n ouL m ouL b) $$meLhod calllng
ConsoleWrlLeLlne(m + m)
ConsoleWrlLeLlne(b + b)
Console8eadLlne()

CU1U1 AkAML1Lk
class ouLpuL

sLaLlc vold cube(ouL lnL y ouL lnL z)

lnL x 2
lnL r 3
y x * x
z r*r*r

publlc sLaLlc vold Maln()

$$lnL n 3
$$lnL d 2 $$no prlor lnlLlallzlng
lnL mb
cube(ouL m ouL b)
ConsoleWrlLeLlne(m + m)
ConsoleWrlLeLlne(b + b)
Console8eadLlne()

CU1U1 AkAML1Lk
class ouLpuL

sLaLlc vold cube(ouL lnL y ouL lnL z)


lnL x 2
lnL r 3
y x * x
z r*r*r

sLaLlc vold area(ouL lnL y ouL lnL z)

lnL x 2
lnL r 3
y x * r
z r * r

publlc sLaLlc vold Maln()


lnL mb $$lnlLlallzaLlon ls noL necessary
cube(ouL m ouL b)
area(ouL m ouL b)
ConsoleWrlLeLlne(m + m)
ConsoleWrlLeLlne(b + b)
Console8eadLlne()

nC1L
lf Lhe same varlables
are used as ouL
parameLer ln more
Lhan one funcLlon Lhen
11here wlll be no
error
2 Lhe ouLpuL wlll be
of Lhe funcLlon whlch
ls execuLed ln Lhe end
Cr Lhe lasL updaLed
value of Lhe varlable
CU1U1 AkAML1Lk
class ouLpuL
sLaLlc vold cube(ouL lnL y ouL lnL z)
lnL x 2
lnL r 3
y x * x
z r*r*r

sLaLlc vold area(ouL lnL y ouL lnL z)


lnL x 1
lnL r 2
y x * r
z r * r

sLaLlc vold area1(ouL lnL y ouL lnL z ouL lnL d)


lnL x 4
lnL r 2
y x * r
z r * r
d z * x

ouLpuL
m2
b4
d16
publlc sLaLlc vold Maln()

cube(ouL m ouL b)
area1(ouL m ouL b ouL c)
area(ouL m ouL b)
ConsoleWrlLeLlne(m + m)
ConsoleWrlLeLlne(b + b)
ConsoleWrlLeLlne(d + c)
Console8eadLlne()

CU1U1 AkAML1Lk
!#%# ##
Aparameter array is an array oI parameters .
It allows a programmer to pass any number oI arguments to
the member oI a method .
It is declared with the 5aram8 modiIier.
II you pass a single array the parameter acts as a normal
value parameter.
It is not possible to combine the 5aram8 modiIier with the
ref and out modiIiers.
!#%# ##
!arameter arrays are declared using the keyword params.
Example
;oid fun1(5aram8 int ] x)

...
....]
x has been declared as a parameter array.
uslng SysLem
class params1

sLaLlc vold array(params lnL a)

ConsoleWrlLeLlne(array elemenLs are)


foreach(lnL l ln a)
ConsoleWrlLe(L+l)
ConsoleWrlLeLlne()
Console8eadLlne()

publlc sLaLlc vold Maln()

lnL x102030
$$array(x) $$call1
array() $$call2
array(1213) $$call3

Lxamp|e of Array arameter


!array() is similar to
!array(new int||});
!array(1000)
Is equivalent to
!array(new int||10000});
uslng SysLem
namespace funcLlon1pr[

class Class1
publlc sLaLlc lnL geLsum(params lnL number)

lnL sum10
foreach(lnL num ln number)
sum1+num
reLurn sum1

publlc sLaLlc vold Maln(sLrlng args)

ConsoleWrlLeLlne(Lhe sum ls)


ConsoleWrlLeLlne(geLsum(1234367))
ConsoleWrlLeLlne(geLsum(1436))
Console8eadLlne()

Lxamp|e of Array arameter


!arameter arrays can also be used as type object.
Example:
public static void Main()

objarray(1mca);
}
static void objarray(params object||x)

Ioreach(object I in x);

Console.Writeline(I);
}
}
Lxamp|e of Array arameter
meLhod ob[array ls
passed for an array of
ob[ecL references 1he
meLhod auLomaLlcally
bullds an ob[ecL array Lo
hold argumenLsboxlng
value Lypes as necessary
ML1nCD CVLkLCADING
Method with the same name but with diIIerent parameter
lists and diIIerent deIinitions.
It is used when methods are required to perIorm similar
tasks but using diIIerent input parameters
Method`s return type does not play any role in the overload
resolution.
Example
int add(int aint b);
int add(intaint bint c);
double add(Iloat xIloat y)
AkkAS
An array is a group oI contiguous or
related data items that shares a common
name.
Every array type inherits the members
declared by the System.Array type.
CkLA1ING AN AkkA
Arrays must be declared and created in the memory beIore
they are used.
Creation oI an array involves three steps:
1.Declaring the array.
.Creating Memory locations.
3.!utting values into the memory locations.
Dec|arat|ons of AkkAS
Syntax
type| | arrayname;
Example:
int|| number; //declare int array reIerence
Iloat| | marks;
int| | xy //declare two int array reIerences
ote:
Don`t enter the size oI the arrays in the declaration.
Creat|on of AkkAS
Create arrays using ew operator .
Syntax:
arraynamenew ty5e8ize];
Example:
number new int|5|;
salarynew Iloat|10|;
ote:
Creation and declaration can be done together also:
int || numbernew int|5|;
Creat|on of AkkAS |n memory
SLaLemenL
|nt number
kesu|t
polnLs no
where
number
numbernew |nt3
polnLs Lo lnL
ob[ecL
number
number0
number1
number2
In|t|a||zat|on of Arrays
ut va|ues |nto array created
SynLax
arraynamesubscrlpLvalue
Lxample
lnL number new number3
number021
number12
number214

Lype arraynamellsL of values


|nt number21214
|nt number new |nt321214
noLe
1o access an array beyond boundarles (number3 )wlll generaLe an error
message
AkkAS
Asslgn an array ob[ecL Lo anoLher
lnL a123
lnL b
ba
8oLh Lhe arrays a and b wlll have Lhe same values
Lvery member ln an array ls auLomaLlcally seL Lo defaulL values
C# array can also hold reference Lype elemenLs An array reference
Lypes wlll conLaln only references Lo Lhe elemenLs and noL Lhe acLual
values
8eference Lypes ln an array are auLomaLlcally lnlLlallzed Lo null
An aLLempL Lo access an elemenL ln an array of reference Lypes
before Lhey are lnlLlallzed wlll cause an error
EXAMPLE OF Single Dimensional Array
//Example of Single dim array
using System;
class class1
{
public static void Main()
{
Console.WriteLine("Single Dimension Array Sample");
string[] strArray = new string[] { "varun", "sonam", "Raj ", "Preet
Kumar"};
// Read array items using foreach loop
foreach (string str in strArray)
{
Console.WriteLine(str); // to print array
}
Console.WriteLine("-----------------------------");
Console.ReadLine();
}}
CuLpuL
Slngle ulmenslon Array Sample
varun
sonam
8a[
reeL kumar

uslng SysLem
namespace Array1

class rogram

sLaLlc vold Maln(sLrlng args)

lnL array1000111
foreach (lnL l ln array1)
ConsoleWrlLe(l)
Console8ead()

Using foreach
uslng SysLem
namespace Array1

class rogram

sLaLlc vold Maln(sLrlng args)



lnL array1 000
111

lnL n array1LengLh
ConsoleWrlLeLlne(lengLh + n)
for (lnL l 0 l 2 l++)

for (lnL [ 0 [3 [++)

ConsoleWrlLe( + array1l[)

ConsoleWrlLeLlne(n)

Console8ead()


Using for Loop
1WC DIMLNSICNAL AkkAS
lor creaLlng Lwodlmenslonal
lnLmyarray
myarray new lnL34
Cr
lnL myarary new lnL34
lnL array1000111
Cr
lnL array1
000
111

8eLrleves Lhe value sLored ln 2 d by uslng subscrlpLs


Lxample lnL value arraay111
EXAMPLE OF ulti-Dimen8ion rray
//Example of Multi-Dimension Array
using System;
class class1

public static void Main()

Console.WriteLine("Multi-Dimension Array Sample");


string|| stringDArray new string| | "Rosy" "Amy" } "!eter" "Albert" } };
Ioreach (string str in stringDArray)

Console.WriteLine(str);
}
Console.WriteLine("-----------------------------");
Console.ReadLine();
}}
CuLpuL
MulLlulmenslon Array Sample
8osy
Amy
eLer
AlberL

kun t|me s|ze dec|arat|on


cIass MainClass
{
static void Main()
{
string[] arr;
Console.Write("How many items on the list? ");
int size = int.Parse(Console.ReadLine());
arr = new string[size];
}
}
VAkIA8LL SI2L AkkAS
Iarlable slze arrays are called [agged arrays
lnL xnew lnL3 $$Lhree rows
x0 new lnL2 $$1
sL
row has 2 elemenLs
x1 new lnL4
x2new lnL3
VAkIA8LL SI2L AkkAS
ecIaring Jagged Arrays
Declaration oI a jagged array involves two brackets. For
example
int|||| JaggedArray new int|3|||;
string|||| string JaggedArray new string||||;
VAkIA8LL SI2L AkkAS
int|||| JaggedArray new int|3|||;
nitializing 1agged rray8
eIore a jagged array can be used its items must be initialized.
// Initializing jagged arrays
JaggedArray|0| new int||;
JaggedArray|1| new int|4|;
JaggedArray|| new int|6|;
We can also initialize a jagged array's items by providing the values oI
the array's items
// Initializing jagged arrays
JaggedArray|0| new int|| 1};
JaggedArray|1| new int|4|4 14 4 34};
JaggedArray|| new int|6| 6 16 6 36 46 56 };
VAkIA8LL SI2L AkkAS
nitializing 1agged rray8
int|||| JaggedArray3

new int|| 1}
new int|| 14 14 4 34}
new int|| 6 16 6 36 46 56}
};
VAkIA8LL SI2L AkkAS
cce88ing 1agged rray8
We can access a jagged array's items individually in the Iollowing way:
Console. Write(JaggedArray|0||0|);
Console.WriteLine(JaggedArray|||5|);
We can also loop through all oI the items oI a jagged array. %he Length
property oI an array helps a lot; it gives us the number oI items in an array.
uslng SysLem
class [aggarr

sLaLlc vold Maln(sLrlng args)

$$declare Lhe [agged arrays


lnL [agarr new lnL3
[agarr0 new lnL2
[agarr1 new lnL3
[agarr2 new lnL4
$$[agarr3new lnL2
$$place Lhe value ln few poslLlon
[agarr01 23
[agarr10 43
[agarr11 26
[agarr21 33
for (lnL l 0 l 2 l++)

ConsoleWrlLeLlne(flrsL row avallable


daLa001 l [agarr0l)

for (lnL l 0 l 3 l++)

ConsoleWrlLeLlne(second row avallable


daLa101 l [agarr1l)

for (lnL l 0 l 4 l++)

ConsoleWrlLeLlne(flrsL row avallable


daLa001 l [agarr2l)

Console8eadLlne()

ExampIe of Jagged Array


CuLpuL of prevlous program sllde
flrsL row avallable daLa000
flrsL row avallable daLa0123
second row avallable daLa1043
second row avallable daLa1126
second row avallable daLa120
Lhlrd row avallable daLa200
Lhlrd row avallable daLa2133
Lhlrd row avallable daLa220
Lhlrd row avallable daLa230
Array is derived Irom the $y8tem.rray class. It
has number oI methods that can be used to
manipulate arrays more eIIiciently.
etLength()
Length
Clear()
Copy%o()
SetValue()
Reverse()
Sort()
METHO$ Of Array
1A88A? LengLh
ln C# all arrays are classbased and sLore Lhe allocaLed slze ln
a varlable named LengLh
lor example
lnL numbernew number3123
We can flnd Lhe lengLh of Lhe array number uslng
numberLength
class params1
{
public static void Main()
{
int [] arr = { 1, 2, 3 };
for(int s=0; s<arr.Length;s++)
Console.Write("\t elements are "+arr[s]);
Console.ReadLine();
}
}
Syntax is
arrayname.GetLength(int dimension)
Type of dimension is System.nt32
cla88 MainClass

5ublic 8tatic ;oid Main() // ouLpuL 43

string|| names
"J" "M" "!"}
"S" "E" "S"}
"C" "A" "W"}
"" "!" "J"}
};
int numberOfRows = names.GetLength(0);
int numberOfColumns = names.GetLength(1);
Console.WriteLine("Number of rows = " + numberOfRows);
Console.WriteLine("Number of columns = " + numberOfColu
mns);
}} // for rows use 0 and for column use 1
2CeLLengLh()
Lxcept|ons of GetLength( )
lndexCuLCf8angeLxcepLlon lf dimension is less
than zero.
-or-
dimension is equal to or greater than array size
Iear()
It sets a range oI elements to empty values or to set them
zero.
Syntax:
rray.Clear(name of the array, 8taring index, la8t
index);
Iear()
using System;
class Program
{
static void Main()
{
int[] array1 = new int[] { 4, 6, 8, 1, 3 };
// Display the array
Console.WriteLine("--- array1 before ---");
foreach (int value in array1)
{
Console.WriteLine(value); }
// Clear all elements in the array.
ArrayIear(array1, 0,array1Length);
//Display the array
Console.WriteLine("--- array1 ---");
foreach (int value in array1)
{
Console.WriteLine(value); }
Console.ReadLine();
}
}
CuLpuL
array1 before
4
6
8
1
3
array1
0
0
0
0
0
Iear()
using System;
class ArrayClear
{
public static void Main()
{
int[] integers = { 1, 2, 3, 4, 5 };
DumpArray("Before: ", integers);
ArrayIear(integers, 1, );
DumpArray("After: ", integers);
}
public static void DumpArray(string title, int[] a)
{
Console.Write(title);
for (int i = 0; i < a.Length; i++)
{
Console.Write("[{0}]: {1, -5}", i, a[i]);
}
Console.WriteLine();
Console.ReadLine();
} }
CuLpuL
8efore 0 1 1 2 2 3 3 4 4 3
AfLer 0 1 1 0 2 0 3 0 4 3
4. CopyTo()
Copies the elements from the source array into the dimension
array.
Syntax:
pubIic void opyTo( Array array, int index )
Parameters
array Type: System.Array
The one-dimensional Array that is the destination of the elements
copied from the current Array.
index Type: System.nt32
A 32-bit integer that represents the index in array at which
copying begins.
opyTo( int offset of source array, destination array name,
int index of destarray ,int no of eIements )
using System;
class Program
{
static void Main()
{
// Declare a string constant and an output array.
string value1 = "welcome to Thapar";
char[] array1 = new char[6];
vaIue1opyTo(2, array1,0,5);
// Output the array we copied to.
Console.WriteLine("--- Destination array ---");
Console.WriteLine(array1.Length);
Console.WriteLine(array1);
Console.ReadLine();
}
}
CuLpuL
value1Copy1o(2 array103)
uesLlnaLlon array
6
lcome
Array1lengLh 7
CuLpuL
value1Copy1o(4 array123)
uesLlnaLlon array
7
ome L
4. CopyTo()
oth Co5y%o() and Clone() make shallow copy (data is
copied) and used Ior Single Dimension arrays.
Clone() method makes a clone oI the original array. It
returns an exact length array.
Co5y%o() copies the elements Irom the original array to the
destination array starting at the speciIied destination array
index. ote that this adds elements to an already existing
array.
Difference Between CopyTo() and Clone()
5. #everse()
Reverses the sequence oI the elements in
the entire one-dimensional Array.
Syntax
public static void Reverse( Array array )
public static void Main()
{
int[] arry = { 12, 3, 89, 27, 20, 54 };
Console.WriteLine("original data");
foreach (int i in arry)
Console.Write("," + i);
Console.WriteLine("\n................");
//Reverse
Console.WriteLine("after Reverse");
Array#everse(arry);
foreach (int i in arry)
Console.Write("," + i);
Console.WriteLine("\n................");
Console.ReadLine();
}
}
Output:
original data
12,3,89,27,20,54
................
after Reverse
54,20,27,89,3,12
................
ExampIe Of #everse
. $O#T()
Sorts the elements in one dimensional.
Array can be sorted using static method rray.8ort
which internally use Quicksort algorithm.
%o sort array oI primitive types such as int double or
8tring use method Array.Sort(Array)with the array as a
paramater.
%he primitive types implements interIace
Com5arable which is internally used by the Sort method
. (it calls IComparable.Com-pare%o method)
//sort int array
using System;
class sort

public static void Main()

int|| intArray new int|5| 8 10 6 3 };


rray.$ort(intArray);
// write array
Ioreach (int i in intArray)
Console.Write(i " ");
}}
// output: 2 3 6 8 10
. $O#T()
// sort string array
using System;
class sort

public static void Main()

string[] stringArray = new string[5] { "X", "B", "Z", "Y", "A" };


Array$ort(stringArray);
// write array
foreach (string str in stringArray) Console.Write(str + " ");
}}
// output: A B X Y Z
Example of $O#T()
public static void Main()

int|| arry 1 3 89 0 54 };
Console.WriteLine("original data");
Ioreach (int i in arry)
Console.Write("" i);
Console.WriteLine("\n................");
rray.$ort(arry);
Ioreach (int i in arry)
Console.Write("" i);
Console.WriteLine("\n................");
rray.#e;er8e(arry);
Ioreach (int i in arry)
Console.Write("" i);
Console.WriteLine("\n................");
Console.ReadLine();
}
CuLpuL
orlglnal daLa
12389272034
______________________
31220273489
___________________
afLer 8everse
89342720123

. Example of $O#T()
noLe
8y defaulL sorL meLhod glves Lhe
ascend|ng order lf you wanL Lhe
order ln descendlng order Lhen
flrsL lmplemenL sorL() Lhen
reverse()
Get VaIue & $et VaIue
et Value :ets the value oI given Index
in the array.
SetValue:-Sets the value oI given Index
in the array.
using System;
public class SamplesArray

public static void Main()

// Creates and initializes a one-dimensional array.


String[] myArr1 = new String[5];
// Sets the element at index 1&3.
myArr1.SetValue("one", 1);
myArr1$etVaIue("three", 3);
Console.WriteLine("[1]: {0}", myArr1GetVaIue(1));
Console.WriteLine("[3]: {0}", myArr1GetVaIue());
/*foreach (string str in myArr1)
Console.WriteLine("{0}", str);*/
Console.Read();
}
}
CuLpuL
1 one
3 Lhree
ExampIe of GetVaIue() and $et VaIue()
lf you are uslng
foreach loop code
CuLpuL
1 one3 Lhree
one
Lhree
using System;
public class SamplesArray

public static void Main()

//d
string|| namenew string ||;
name.SetValue("MCA"00);
name.SetValue("%hapar"01);
name.SetValue("!atiala"10);
name.SetValue("!unjab"11);
Console.WriteLine("|00| 0}" name.etValue(00));
Console.WriteLine("|01| 0}" name.etValue(01));
Console.WriteLine("|10| 0}" name.etValue(10));
Console.WriteLine("|11| 0}" name.etValue(11));
Console.Read();
}
}
CuLpuL
00 MCA
01 1hapar
10 aLlala
11 un[ab
ExampIe of GetVaIue() and $et VaIue()
ArgumentException :
The current Array does not have exactly one dimension.
ArgumentOutOfRangeException :index is outside the range of valid
indexes for the current Array.
EXEPTION in GetVaIue() &$et VaIue()
A##AYLI$T LA$$
ArrayList is one oI the most Ilexible data structure Irom CSharp
Collections.
ArrayList class is deIined under the $y8tem.Collection8
name85ace.It must be included.
ArrayList contains a simple list oI values.
ArrayList implements the i8t interface using an array and
very easily we can add insert delete view etc.
It is very Ilexible because we can add without any size
inIormation that is it will grow dynamically and also shrink .
A##AYLI$T METHO
Add() : Add an Item in an ArrayList
Insert() : Insert an Item in a speciIied position in an ArrayList
Remove() : Remove an Item Irom ArrayList
RemoveAt(): remove an item Irom a speciIied position
Sort() : Sort Items in an ArrayList
Clear():Removes the elements Irom the list.
Count:ets the number oI elements currently in the list.
Capacity:ets or sets the number oI elements currently in the list
A##AYLI$T LA$$
An Array list is similar to an array except that it has
ability to grow dynamically
ArrayList c1 new ArrayList(5);
It creates a c1 with ca5acity to store 5 objects.
y deIault the capacity is sixteen.
ArrayList c1 new ArrayList();
c1.capacity5;
ow to add an Item in an ArrayList ?
dd()
$yntax : ArrayList.add(object)
object : %he Item to be add the ArrayList ArrayList arr;
arr.dd("Item1");
ow to Insert an Item in an ArrayList ?
n8ert()
Syntax : ArrayList.insert(indexobject)
index : %he position oI the item in an ArrayList
object : %he Item to be add the ArrayList ArrayList arr;
arr.Insert(3 "Item3");
A##AYLI$T LA$$
ow to remove an item Irom arrayList ?
#emo;e()
Syntax : ArrayList.Remove(object)
object : %he Item to be remove Irom the ArrayList arr:
arr.Remove("item")
ow to remove an item in a speciIied position Irom an
ArrayList ?
#emo;et()
Syntax : ArrayList.RemoveAt(index)
index : the position oI an item to remove Irom an ArrayList arr:
arr.RemoveAt()
ow to sort ArrayList ?
$ort()
Syntax : ArrayList.Sort()
A##AYLI$T LA$$
Reverse an item Irom arrayList ?
#e;er8e()
Syntax : ArrayList.Reverse()
object : %heArraylist get reverse
arr.Reverse()
Removes all the item Irom the List
Clear()
Syntax:ArrayList.Clear();
Object:%he Arraylist will be empty.
arr.clear()
Determines iI an element is in the list or not
Contain8()
Syntax:ArrayList.Contains(object);
Return type is bool
A##AYLI$T LA$$
Example Of ArrayList
using System;
using System.Collections;
namespace Arraylist

class !rogram

static void Main(string|| args)

ArrayList n new ArrayList();


Console.WriteLine("Capacity" n.Capacity);
n.Add("A1");
n.Add("S");
n.Add("V3");
n.Add("!4");
n.Add("D5");
Console.WriteLine("elements present" n.Count);
n.Sort();
Ior(int i0;in.Count;i)

Console.WriteLine(n|i|);
}
Console.WriteLine();
n.#emo;e#ange(1,2); remo;e8 the 1 n 2
nd
index
element
n.#emo;et(3);
n.Clear();
n.n8ert(3, "geet");
Ior (int i 0; i n.Count; i)

Console.WriteLine(n|i|);
}
Console.ReadLine();
}
}
}
continuation Example Of ArrayList
using System;
using System.Collections;
class MainClass
static void Main(string|| args)

ArrayList a new ArrayList(10);


int x 0;
a.Add(x);
a.Add(x);
a.Add(x);
a.Add(x);
a.Add("e");
Ior (int i 0; i a.Count; i)

Console.WriteLine(a|i|);
}
Console.ReadLine();
bool b a.Contains(x);
Console.WriteLine("the value oI b is" b);
Console.WriteLine("aIter removing");
a.#emo;e(x);
bool ba.Contain8("g");
Console.WriteLine("the value oI b is" b);
a.#emo;et(0);
Ior (int i 0; i a.Count; i)

Console.WriteLine(a|i|);
}
a.Clear();
bool b1 a.Contains(x);
Console.WriteLine("the value oI b is" b1);
Console.WriteLine("clear");
Ior (int i 0; i a.Count; i)

Console.WriteLine(a|i|);
}
Console.ReadLine();
}
}
Example Of ArrayList
CHANGE CONTENTS USNG ARRAY NDEXNG
u8ing System;
u8ing System.Collections;
cla88 arrali8t1

5ublic 8tatic ;oid Main()


ArrayList al new ArrayList();
Console.WriteLine("Adding 6 elements");
// Add elements to the array list
al.Add('C');
al.Add('A');
al.Add('E');
al.Add('');
al.Add('D');
al.Add('F');
Console.WriteLine("Change Iirst three elements");
al|0| 'X';
al|1| 'Y';
al|| 'Z';
Console.Write("Contents: ");
Ioreach(char c in al)
Console.Write(c " ");
Console.WriteLine(); } }
#emove EIements From List
using System;
using System.Collections;
cIass MainClass {
pubIic static void Main() {
ArrayList al = new ArrayList();
Console.WriteLine("Adding 6 elements");
// Add elements to the array list
al.Add('C');
al.Add('A');
al.Add('E');
al.Add('B');
al.Add('D');
al.Add('F');
Console.WriteLine("Removing 2 elements");
// Remove elements from the array list.
al.Remove('F');
al.Remove('A');
Console.WriteLine("Number of elements: " +
al.Count);
}}
$ort and $earch ArrayList
us|ng SysLem
us|ng SysLemCollecLlons
c|ass sortsearch
pub||c stat|c vo|d Maln()
$$ creaLe an array llsL
ArrayLlsL al new ArrayLlsL()
$$ Add elemenLs Lo Lhe array llsL
alAdd(133)
alAdd(413)
alAdd(41)
alAdd(818)
alAdd(31)
alAdd(191)
ConsoleWrlLe(Crlglnal conLenLs )
foreach(|nt l ln al)
ConsoleWrlLe(l + )
ConsoleWrlLeLlne(n)
$$ SorL
alSorL()
$$ Dse foreach loop Lo dlsplay Lhe llsL
ConsoleWrlLe(ConLenLs afLer sorLlng )
foreach(|nt l ln al)
ConsoleWrlLe(l + )
ConsoleWrlLeLlne(n)
ConsoleWrlLeLlne(lndex of 413 ls + al8lnary
Search(413))

You might also like