Professional Documents
Culture Documents
synLax
modiIiers return-type method-name( Iormal parameter list )
lnL x (a b) ? a b
reLurn x
class nesLLesL
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
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
Console.WriteLine("hello");
nonstaticmethod obj new nonstaticmethod();
obj.Cube(4);
}
void Cube(Iloat x) //method is not static
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
class x2
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
m m + 23
ConsoleWrlLeLlne(Lhe value of x lnslde funxLlonls + m)
Console8eadLlne()
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
lnL Lempx
xy
yLemp
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
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
lnL x 2
lnL r 3
y x * x
z r*r*r
$$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
lnL x 2
lnL r 3
y x * r
z r * r
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
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
lnL x102030
$$array(x) $$call1
array() $$call2
array(1213) $$call3
class Class1
publlc sLaLlc lnL geLsum(params lnL number)
lnL sum10
foreach(lnL num ln number)
sum1+num
reLurn sum1
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
uslng SysLem
namespace Array1
class rogram
lnL array1000111
foreach (lnL l ln array1)
ConsoleWrlLe(l)
Console8ead()
Using foreach
uslng SysLem
namespace Array1
class rogram
lnL n array1LengLh
ConsoleWrlLeLlne(lengLh + n)
for (lnL l 0 l 2 l++)
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
Console.WriteLine(str);
}
Console.WriteLine("-----------------------------");
Console.ReadLine();
}}
CuLpuL
MulLlulmenslon Array Sample
8osy
Amy
eLer
AlberL
Console8eadLlne()
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
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
//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
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)
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