Upload
shital-khokhar
View
221
Download
1
Embed Size (px)
Citation preview
8/13/2019 Net Material
1/45
Windows DNA
Windows DNAis short for Windows Distributed interNet ApplicationsArchitecture. DNA is a Microsoft blueprint for robust, scalable, distributed business software.In Short, its a collection of Microsoft technologies that enable the Windows platform and theInternet to work together. Windows DNA is a eolution which started from mainframes, !o"pro ages, #$% & S'( S)*#)* ,+hree tier which was mainl -M where business logic resided,
-M/ and finall the DNA. Some of the principal technologies comprising DNA includeActie0, Dnamic 1+M( 2D1+M(3 and -M. Microsoft no longer uses this term.
Microsoft .NET :.N)+ is a platform that proides a standardi4ed set of serices..N)+ is a platform that proides a standardi4ed set of serices.
Features :
Its 5ust like Windows, e"cept distributed oer the Internet.Its 5ust like Windows, e"cept distributed oer the Internet. Its a powerful and robust software deelopment technolog
It e"ports a common interface so that its programs can be run on an sstem thatIt e"ports a common interface so that its programs can be run on an sstem thatsupports .N)+.supports .N)+.
6roides a multi7language deelopment platform, so ou can work in the programminglanguage ou prefer.
It proides the securit adancements, management tools, and updates ou need tobuild, test, and deplo highl reliable and secure software.
.NET Framework
+he .N)+ !ramework is an integral Windows component that supports building and running thene"t generation of applications and 0M( Web serices. +he .N)+ !ramework is designed tofulfill the following ob5ecties8
Appl common skills across a ariet of deices, application tpes, and programmingAppl common skills across a ariet of deices, application tpes, and programmingtaskstasks
Integrate with other tools and technologies to build the right solution with less workIntegrate with other tools and technologies to build the right solution with less work $uild compelling applications faster$uild compelling applications faster
+he .N)+ !ramework has two main components8
Common anguage !untime .N)+ Framework Class ibrar.
$ proiding, a comprehensie and consistent programming model and a common set of A6Is,the .N)+ !ramework helps to build applications that work the wa ou want, in theprogramming language ou prefer, across software, serices, and deices.
C! "Common an#ua#e !untime$
A runtime that is usable b different and aried programming languages. -(* is core component of Microsoft .N)+. +he common language runtime is the foundation of the .N)+ !ramework. -(* also called .N)+ *untime in short. Its a framework laer that resides aboe the S and handles the e"ecution of all
8/13/2019 Net Material
2/45
the .N)+ applications. 6rogram doesnt directl communicate with the S but go through the-(*.
-(* is an agent that manages code at e"ecution time, proiding core serices such asmemor management, thread management, and remoting, also enforcing strict tpe safetand other forms of code accurac that promote securit and robustness. In fact, the conceptof code management is a fundamental principle of the runtime.
At runtime, the -(* has no idea which programming language the deeloper used forthe source code. +his means that ou ma deelop our code in an programming languageou desire as long as the compiler ou use to compile our code targets the -(*.
Microsoft is creating seeral language compilers that target the runtime8 -// withmanaged e"tensions, -9, #isual $asic.N)+, :Script, :aa, and an intermediate language 2I(3
Assembler.
In addition to Microsoft, other companies are also creating compilers that producecode that targets the -(* like Alice, A6(, -$(, -omponent 6ascal, )iffel, !ortran, 1askell,Mercur, M(, Mondrian,beron, 6erl, 6thon, *6;, Scheme, and Smalltalk.
Common Language Runtime (CLR)
Windows OS
.NET Application
8/13/2019 Net Material
3/45
8/13/2019 Net Material
4/45
Natie Compile!
"#T ("ust in Time) Compile!
Mana#ed code e'ecution process
Source Code
MSIL Code
Native Code
CPUOutput
Language #ndependent wit$in.NET %!amewo!&
8/13/2019 Net Material
5/45
Difference between mana#ed code and unmana#ed code :
Managed code is created b b.net and c9 compilers.
+his tpe of code is translated in I( first. Managed code is one that is run b -(* of the .N)+ framework. It is e"ecuted under the instructions of -(*.
?nmanaged code is what was used before #isual Studio .N)+ =>>= was released. It is translated directl into machine language. ?nmanaged code is one that is run b windows operating sstem. +he -(* cannot instruct the code.
M() "Microsoft )ntermediate an#ua#e$ Code
When compiling .Net compliant 6rogram 2Managed -ode3, the source code does not getconerted into the e"ecutable binar code, but the compiler translates it into intermediatecode known as MSI( which is interpreted b the -ommon (anguage *untime. MSI( code is a-6? 21ardware and S3 independent set of instructions that can be efficientl conerted tonatie code.
At the time of program e"ecution, this MSI( 2intermediate code3 is conerted to binare"ecutable code 2Natie -ode3. -ross language relationships are possible as the MSI( code issimilar for each .Net language.
8/13/2019 Net Material
6/45
When a compiler produces MSI(, it also produces metadata. Metadata describes the tpes inour code, including the definition of each tpe, the signatures of each tpe@s members, themembers that our code references, and other data that the runtime uses at e"ecution time.+he MSI( and metadata are contained in a portable e"ecutable 26)3 file. +his file format, whichaccommodates MSI( or natie code as well as metadata, enables the operating sstem torecogni4e common language runtime images. +he presence of metadata in the file together
with MSI( enables the code to describe itself.
*ust )n Time "*)T$ Compilers
*ust+in+time compilation2*)T3, also known as d,namic translation. +his is a techni
8/13/2019 Net Material
7/45
-+S is a set of standards. +he -+S defines how tpes are declared, used, and managed in theruntime. +pes are the mechanism b which code written in one programming language cantalk to code written in a different programming language. -+S defines the basic data tpesthat I( understands.
)ach .Net compliant language should map its data tpes to these standard data tpes. +hismakes it possible for the = languages to communicate with each other b passing&receiing
parameters to and from each other. !or e"ample, -+S defines a tpe, IntB=, an integral datatpe of B= bits 2C btes3 which is mapped b -9 through int and #$.Net through its Integerdata tpe.
+he common tpe sstem supports two general categories of tpes, each of which is furtherdiided into subcategories8
#alue +pe *eference +peValue Type
#alue tpes directl contain their data, and instances of alue.
#alue tpes can be built7in, user7defined, or enumerations.Reference Type
*eference tpes store a reference to the alue@s memor address, and are allocated onthe heap.
*eference tpes can be self7describing tpes, pointer tpes, or interface tpes.
+he tpe of a reference tpe can be determined from alues of self7describing tpes.
Self7describing tpes are further split into arras and class tpes.
+he class tpes are user7defined classes, bo"ed alue tpes, and delegates.
All tpes derie from the Sstem.b5ect base tpe.
Common an#ua#e (pecification "C($-ommon (anguage Specification 2-(S3 makes a language a E.N)+ -ompliant (anguage.Microsoft has released a small set of specifications that each language should meet to
8/13/2019 Net Material
8/45
operator oerloading methods that support a ariable number of parameters
If ou intend to create tpes that are easil accessible from other programming languages,then it is important that ou use onl features of our programming language that areguaranteed to be aailable in all other languages. Microsoft has defined a common language
specification 2-(S3 that details for compiler endors the minimum set of features that theircompilers must support if the are to target the runtime.
-arba#e Collection
+he .N)+ !ramework@s garbage collector manages the allocation and release of memor forour application. )ach time a new ob5ect is created, the common language runtime allocatesmemor for the ob5ect from the managed heap. As long as address space is aailable in themanaged heap, the runtime continues to allocate space for new ob5ects.
1oweer, memor is not infinite so garbage collector has to checks for ob5ects in the managedheap that are no longer being used b the application and performs the necessar operationsto reclaim their memor.
If no more memor is aailable for the heap, then the new operator throws anutfMemor)"ception.
When the garbage collector triggered, it makes the assumption that all ob5ects in the heap aregarbage. It reclaims the memor that is occupied b dead ob5ects. +he reclaiming processcompacts lie ob5ects so that the are moed together, and the dead space is remoed,thereb making the heap smaller. +his ensures that ob5ects that are allocated together statogether on the managed heap, to presere their localit.
A garbage collection has the following phases8
A marking phase that finds and creates a list of all lie ob5ects. A relocating phase that updates the references to the ob5ects that will be compacted.
A compacting phase that reclaims the space occupied b the dead ob5ects.
Automatic Memor, Mana#ement
Automatic memor management is one of the serices that the common language runtimeproides during Managed )"ecution.
+he 6rocess includes Allocation of Memor *elease the Memor
Allocating Memory
When a process is initiali4ed, the runtime reseres a contiguous region of address space forthe process. +his resered address space is called the managed heap. +he heap also maintainsa pointer to the address. +his pointer indicates where the ne"t ob5ect is to be allocated withinthe heap.
8/13/2019 Net Material
9/45
Aboe fig shows a managed heap consisting of three ob5ects8 A, $, and -. +he ne"t ob5ect tobe allocated will be placed where Ne"t b5ect 6ointer points that is immediatel after ob5ect -.When an application creates the first reference tpe, memor is allocated for the tpe at the
base address of the managed heap.
When the application creates the ne"t ob5ect, the garbage collector allocates memor for it inthe address space immediatel following the first ob5ect. As long as address space is aailable,the garbage collector continues to allocate space for new ob5ects in this manner. Allocatingmemor from the managed heap is faster than unmanaged memor allocation. In managedheap new ob5ects that are allocated consecutiel are stored contiguousl in the managedheap, an application can access the ob5ects er
8/13/2019 Net Material
10/45
when the are finished with the ob5ect.
.NET Framework
+he .Net !ramework is the combination of laers of -(*, !-(, Data and 0M( -lasses and ourWindows, Web applications and Web Serices. A diagram of the .Net !ramework is presentedbelow for better understanding.
istor, of C/
riginated b Microsoft as a response to :aa
Initial public release in =>>>
(ead designers8 Anders 1e5lsberg, Scott Wiltamuth
-9 standardi4ed ia )-MA and IS
1oweer, Microsoft retains architectural control
Features
?nified ob5ect sstem
)erthing tpe is an ob5ect.
Single inheritance
Interfaces Specif methods F interfaces, but no implementation.
Structs
A restricted, lightweight 2efficient3 tpe.
Delegates
)"pressie tpesafe function pointer. ?seful for strateg and obserer design patterns.
6reprocessor Directies
8/13/2019 Net Material
11/45
!ules
-ase7sensitie
Whites pace has no meaning
Semicolons are used to terminate statements 2G3
-url braces H enclose code blocks
First C/ Application
using SstemGnamespace McaJ-SharpH
class 1elloWorld H static oid Main23 H -onsole.Write(ine2K1ello WorldK3G
OutPut : Hello World
Error
namespace McaJ-SharpH
class 1elloWorld H static oid Main23 H
-onsole.Write(ine2K1ello WorldK3G
(a0in#1 Compilin# and E'ecutin# the 2ro#ram
Sae the file with e"tension L.cs .2!irst.cs3
;oto command window and goto the director where the 6rogram is
-ompile the file 8
csc !irst.cs
After successful compilation .)0) file is created 2!irst.)0)3.
)"ecute the )0) file !irst
2AT
If ou receied the Lcommand not found error, the command interpreter couldntlocate the csc.e"e application.
+o remed this, ou need to make the change to a 6ath enironment ariable.
8/13/2019 Net Material
12/45
G-86rogram !ilesMicrosoft #isual Studio SDO=.>$inG-8WINN+Microsoft.N)+!ramework=.>.J>P=PG-86rogram !ilesMicrosoft #isual Studio #-binG-86rogram !iles-ommon !ilesMicrosoft Shared#SA.>#sa)nG
Namespace
+he second line of code that ou see in the demo is the definition of a namespacenamed McaJ-Sharp.
A Namespace is simpl a conenient wa of logical collection of related classes in -9.
+he namespace ma contain classes, eents, e"ceptions, delegates and een othernamespaces
!or )". It is er much possible that our -onnection -lass in DataActiit conflicts withthe -onnection -lass of InternetActiit.
+o aoid this, these classes are made part of their respectie namespace. So the full
8/13/2019 Net Material
13/45
*untime 2-(*3 without making an ob5ect of our 1elloWorld -lass.
+he method is also declared oid as it does not return anthing.
(,stem.Console.Writeine Method
Sstem Q Sstem is a default namespace.
-onsole Q represents standard input, output, error streams for console application.
+his class cannot be inherited.
Write(ine23 7 it is a static method of the -onsole class defined in the Sstem
namespace. +his method takes a string 2enclosed in double U3G
Data T,pes
Numeric Data +pes
?nsigned 2positie3
bte, ushort, uint, ulong
Signed 2positie or negatie3
short, int, long, float, decimal, double
Select the smallest tpe that will hold the re>C3 )scape character 2En3
bool
1olds true or false in one bte
Declarin# ocal 4ariable
8/13/2019 Net Material
14/45
namespace McaJ-SharpH
class AdditionDemo H static oid Main23 H
int a,ansG &&declare multiple ariables.aV>Gint bV=>G &&declare and initiali4edans V a / bG
Sstem.-onsole.Write(ine2K+he addition of two numbers8K/ans3G
OutPut : The Addition of two numbers : 30
using SstemGnamespace McaJ-Sharp
H class ;reet H static oid Main2StringTU args3 H String nameG -onsole.Write(ine2K)nter our Name 8 K3G name V -onsole.*ead(ine23G
-onsole.Write(ine2K1i H> 1ow are ouXK, name3G &&-onsole.Write(ine2L1i / name / 1ow are ouX3G
-onsole.Write(ine2K$e...K / name3G
Output : Enter Your Name : TNR
Hi TNR How are !ou"
Important Point to Remember :
+he entr point to program is the static method Main23 with oid return tpe.
-9 is a case sensitie language so oid and #oid are different.
ou DN@+ need to sae our program with same file name as of our class containingMain23 method.
+here can be multiple Main23 methods in our program.
A namespace is onl logical collection of classes with no phsical mapping on disk
2unlike :aa3.
)nclosing our class in some namespace is optional. ou can write program where
our class is not enclosed b an namespace
It is not mandator that Main Method of program takes @string TU args@ as parameter.
8/13/2019 Net Material
15/45
Multiple Main Method
+he designers of -9 included a mechanism b which ou can define more than oneclass with a Main method.
ou can then use the &main8YclassNameZ switch with the -9 compiler to specifwhich classs Main method to use.
using SstemG
class MainH
static oid Main23H
-onsole.Write(ine2KMainK3G
class Main=H
static oid Main23H
-onsole.Write(ine2KMain=K3G
+o compile this application so that the Main.Main method is used as the applicationsentr point
csc MultipleMain.cs &main8Main
+o compile this application so that the Main=.Main method is used as the applicationsentr point
csc MultipleMain.cs &main8Main=
)mplicit Numerical Con0ersions
sb,te short1 int1 lon#1 float1 double1 decimal
char int1 lon#1 float1 double1 decimal1 ushort1 uint1 ulon#
b,te short1 ushort1 int1 uint1 lon#1 ulon#1 float1 double1 decimal
short int1 lon#1 float1 double1 decimal
ushort int1 uint1 lon#1 ulon#1 float1 double1 decimal
int lon#1 float1 double1 decimal
uint lon#1 ulon#1 float1 double1 decimal
ulon#1 lon# float1 double1 decimal
float doubleNote that some of the aboe conersion will cause loss of precision but not loss of magnitude.
)mplicit Con0ersion E'ample
using SstemGnamespace McaJ-SharpH
class -onertH
public static oid Main23
H
8/13/2019 Net Material
16/45
char cV@A@Gint iVcG-onsole.Write(ine2i3G
long lV=BCJ%P[>>Gfloat fVlG-onsole.Write(ine2f3G &&(oss of 6recision
OutPut : 65
2.345679E+!
Con0erts (trin# to )nte#er
using SstemGnamespace McaJ-SharpH class S
8/13/2019 Net Material
17/45
Output :
Enter the Radius : '0
Area of (ir)le is : 3'*
)ntroduction of Classes1 ob5ects and methods
&b5ect
An ob5ect is a region of storage that defines both state F behaior.
(tateis represented b a set of ariables F the alues the contain.
6eha0ioris represented b a set of methods F the logic the implement.
+hus, an ob5ect is a combination of a data F the code that acts upon it.
b5ects are instance of a class.
b5ects are the basic runtime entities in an ob5ect7oriented sstem.
b5ect take up space in memor and hae an associated address like a record in6ascal or structure in -.
b5ects are runtime instance of some class.!or )"ample86erson p,p=Gp V new person23Gp= V new person23G
Class
A class is a template from which ob5ects are created. +hat is ob5ects are instance of aclass.
When ou create a class, ou are creating a new data7tpe. ou can use this tpe todeclare ob5ects of that tpe.
-lass defines structure and behaior 2data F code3 that will be shared b a set of
ob5ects
class -lassNameH
tpe ariableGtpe ariable=G
tpe methodname 2parameter list3H
bod of methodGtpe methodname= 2parameter list3H
bod of methodG
Access Modifiers
Access Modifier Description
8/13/2019 Net Material
18/45
public "igni#ies t$at t$e mem%er is a&&essi%le #rom outsi'e t$e
&lass(s 'e#inition an' $ierar&$) o# 'eri*e' &lasses.
protected T$e mem%er is not *isi%le outsi'e t$e &lass an' &an %e
a&&esse' %) 'eri*e' &lasses onl).
private T$e mem%er &annot %e a&&esse' outsi'e t$e s&ope o# t$e
'e#ining &lass. T$ere#ore not e*en 'eri*e' &lasses $a*e
a&&ess to t$ese mem%ers.
internal T$e mem%er is *isi%le onl) ,it$in t$e &urrent &ompilation
unit. T$e internala&&ess mo'i#ier &reates a $)%ri' o# publican'protecteda&&essi%ilit) 'epen'ing on ,$ere t$e &o'e
resi'es.
using SstemGnamespace McaJ-SharpH class $o" H
internal double widthG
internal double heightG internal double depthG
class $o"Demo H
static oid Main 23 H $o" mbo" V new $o" 23G double olG mbo".width V>G mbo".height V =>G mbo".depth V B>G ol V mbo".width R mbo".height R mbo".depthG -onsole.Write(ine2K#olume is8 7 K /ol3G
)ach ob5ect contains its own cop of each ariable defined b the class.
So, eer $o" ob5ect contains its own cop of the instance ariables width, height anddepth.
+o access these ariables, ou will use the dot 2.3 operator. +he dot operator links the
name of the ob5ect with the name of an instance ariable.
Declarin# &b5ect
' $o" mbo"G && declare ref. to ob5ect which contains null alue.
8/13/2019 Net Material
19/45
' mbo" V new $o" 23G && allocate a $o" ob5ect.
-eneral form of a new
class ar V new classname 23Gmbo" V new $o" 23G
Where8class ar V ariable of the class tpe.classname V name of the class.
+he classname followed b parentheses specifies the constructor for the class.
A constructor defines what occurs when an ob5ect of a class is created.
Most classes e"plicitl define their own constructors within their class definition but if
no e"plicit constructor is specified then -9 will automaticall suppl a default constructor.
+his is the case with $o". +his is default constructor.
Assi#nin# &b5ect !eference 4ariable
$o" b V new $o" 23G$o" b= V new bG
After this e"ecutes, b and b= will both refer to the same ob5ect.
+he assignment of b to b= did not allocate an memor or cop an part of the
original ob5ect.
It simpl makes b= refer to the same ob5ect as does b. +hus, an changes made to
the ob5ect through b= will affect the ob5ect to which b is referring, since the are the sameob5ect.
)ntroducin# Methods
tpe name 2parameter7list3H
bod of method
Where8
T,pe : Specifies the tpe of data returned b the method. If the method does not return aalue its return tpe must be oid.
Name: Specifies the name of the method.
2arameter+list: It is a se
8/13/2019 Net Material
20/45
using the following form of the return statementG!eturn 0alue7
T,pes of Methods
Does not return 0alue 8 0oid
!eturnin# a 0alue Method which takes parameter
Does not return 0alue 8 0oid
using SstemGnamespace McaJ-SharpH
class $o"H
internal double width, height, depthGinternal oid olume23
H -onsole.Write(ine2L#olume is8 7L/widthRheightRdepth3G
class $o"Demo#oid
Hstatic oid Main 23H
$o" M$o" V new $o" 23G$o" M$o"= V new $o" 23G
M$o".width V>GM$o".height V=>G
M$o".depth VJGM$o"=.width V>GM$o"=.height VJGM$o"=.depth V=JGM$o".olume 23GM$o"=.olume 23G
!eturnin# a 0alue
using SstemGnamespace McaJ-Sharp
Hclass $o"H
internal double width, height, depthGinternal double olume23H
return widthRheightRdepthG
8/13/2019 Net Material
21/45
class $o"Demo+peH
static oid Main 23H
$o" M$o" V new $o" 23G$o" M$o"= V new $o" 23Gdouble olG
M$o".width V>GM$o".height VJGM$o".depth V=>GM$o"=.width V=GM$o"=.height VBGM$o"=.depth VJG
ol V M$o".olume 23G
-onsole.Write(ine 2L#olume is8 7L/ol3G
ol V M$o"=.olume 23G-onsole.Write(ine 2L#olume is8 7L/ol3G
Method which takes parameter
int s R >G
It will return the s but this method is specified to onl >. If ou modif themethod so that it takes a parameter.int s3, passes >> as an argument.
using SstemG
namespace McaJ-SharpH
class $o"H
internal double width, height, depthGinternal double olume23H
return widthRheightRdepthGinternal oid SetDim 2double w, double h, double d3H
width V wG
8/13/2019 Net Material
22/45
8/13/2019 Net Material
23/45
internal double olume23H
return widthRheightRdepthG
class $o"Demo-onH
static oid Main 23H
double olG$o" M$o" V new $o" 23G$o" M$o"= V new $o" 23G
ol V M$o".olume 23G
-onsole.Write(ine2L#olume is8 7L/ol3G
ol V M$o"=.olume 23G-onsole.Write(ine 2L#olume is8 7L/ol3G
M$o" and M$o"= were initiali4ed b the $o" 23 constructor when the were
created.
$oth will print the same alue >>>.
6o' M,6o'9 new 6o' "$7
-onstructor for the class is being called. New $o"23 is calling the $o"23 constructor.
2arameteri;ed Constructor
using SstemG
namespace McaJ-SharpH
class $o"H
internal double width, height, depthGinternal $o" 2double w, double h, double d3H
width V wGheight V hGdepth V dG
internal double olume23H
return widthRheightRdepthG
class $o"Demo-on6araH
static oid Main 23H
double olG
8/13/2019 Net Material
24/45
8/13/2019 Net Material
25/45
d.test2>3Gd.test2>,=>3G
Constructor &0erloadin#
In addition to oerloading normal methods, we can also oerload constructor methods.
class $o"H
internal double width, height, depthGinternal $o" 2double w, double h, double d3H
width V wGheight V hGdepth V dG
internal $o"23
Hwidth V JGheight V JGdepth V JG
internal $o" 2double len3H
width V height V depth V lenGinternal double olume23H
return widthRheightRdepthG
class erload-onsH
static oid Main 23H
$o" M$o" V new $o"2>,=>,J3G$o" M$o"= V new $o"23G$o" M-ube V new $o"2P3Gdouble olGol V M$o".olume23G-onsole.Write(ine2K#olume of M$o" is8 K/ol3G
ol V M$o"=.olume23G-onsole.Write(ine2K#olume of M$o"= is8 K/ol3Gol V M-ube.olume23G
-onsole.Write(ine2K#olume of M-ube is8 7K/ol3G
OutPut :
+olume of ,!-o.' is 3000
+olume of ,!-o.& is '
+olume of ,!(ube is 3*3
8/13/2019 Net Material
26/45
&b5ect as 2arameter
class +est 23H
internal int a, bG
internal +est 2int i, int 53Ha V iGb V 5G
internal bool e>,==3G+est ob= V new +est 2>>,==3G+est obB V new +est 27,73G-onsole.Write(ine2Lob VV ob=/ob.e
8/13/2019 Net Material
27/45
runtime generates a cop and passes that cop to the method. It is actuall a cop of theariable that is aailable inside the method.
1ence if ou modif a alue tpe ariable 2passed as a parameter3 in a method, theactual alue of the ariable would not be changed outside the method.
class +estHinternal oid meth 2int i, int 53H
i V iR=G5 V 5&=G
class -all$#alueH
static oid Main23H
+est t V new +est23Gint aVJ, bV=>G
-onsole.Write(ine2Ka F b before call8 7 K/a/K K/b3G+.meth 2a,b3G-onsole.Write(ine2Ka F b after call8 7K/a/K K/b3G
Output:
A and b before call: 15 !A and b after call: 15 !
' $ecause a cop of the ariable a and b is passed to the maths23 method and not theariable a and b .
' Also, note that i and 5 are the local ariable in maths23 and a and b are local ariablesin Main23. 1ence, the can be accessed within their containing methods onl.
Call+6,+!eference
A reference to an argument 2not alue of argument3 is passed to the parameter.
Inside the subroutine, this reference is used to access the actual argument specified in
the call. +his means that changes made to the parameters will affect the argument used to callthe subroutine.
ref and out ke,words
-9 proides a keword
8/13/2019 Net Material
28/45
8/13/2019 Net Material
29/45
#alue tpes are primitie tpes that are mapped directl to the !-(. (ike IntB= mapsto Sstem.IntB=, double maps to Sstem.double. All alue tpes are stored on stack .
An ob5ect of a alue tpe stores its associated data directl within itself.
!or )"ample 8 When we write8
double pi V B.CJ[G the alue B.CJ[ is directl stored within pi.
When we initiali4e or assign one alue tpe with another, the data contained in theone is copied to the second. +he two ob5ects remain independent.
!or e"ample, when we write
double short6i V piG
although both pi and short6i now hold the same alue, the alues are distinct instancescontained in independent ob5ects.
!eference T,pe
*eference +pes are different from alue tpes in such a wa that memor is allocatedto them from the heap.
All the classes are of reference tpe. -9 new operator returns the memor address ofthe ob5ect. *eference tpes are stored on the run7time heapG the ma onl be accessedthrough a reference to that storage.
!or )"ample
+he b5ect +pe
+he class +pe
Interfaces
Delegates
+he string tpe
ArrasMob5 ob5Gob5 V new mob523G
ob5 is reference tpe ariable 2assuming Mob5 is a class tpe ariable3.compilerallocates memor for this ob5ect on the heap and its address is stored in ob5.
6o'in# and %nbo'in#
-9 +pe Sstem contains three +pes 8
#alue +pes
*eference +pes
6ointer +pes.
8/13/2019 Net Material
30/45
-9 allows us to conert a #alue +pe to a *eference +pe, and back again to #alue+pes .
+he operation of -onerting a #alue +pe to a *eference +pe is called $o"ing and thereerse operation is called ?nbo"ing.
6o'in#
+he conersion of alue tpe to reference tpe is known as bo"ing.
A bo"ing conersion permits an alue7tpe to be implicitl conerted to the tpeob5ect or to an interface7tpe implemented b the alue7tpe.
class +estH
static oid Main23H
int i V JG
ob5ect ob5 V iG && bo"ing
int 5 V 2int3 ob5G && unbo"ing-onsole.Write(ine2Lb5ect is H>, ob53G-onsole.Write(ine2L: is H>,53G
+he first line we created a #alue +pe #al and assigned a alue to #al. +he second line, we created an instance of b5ect b5 and assign the alue of #al to b5. !rom the aboeoperation 2b5ect b5 V al 3 we saw conerting a alue of a #alue +pe into a alue of acorresponding *eference +pe .
)nheritance
In b5ect riented 6rogramming the original class 2or the class that is sub7tped3 iscalled the base, parent or super class. +he class that inherits the functionalit of the base classand e"tends it in its own wa is called the sub, child, deried or inherited class.
A base class usuall has general functionalit, while sub7classes possess specificfunctionalit. So, when sub7classing or inheriting, we go 'from generalization tospecialization'.
If a class $ 2sub class3 inherits a class A 2base class3, then $ would hae a cop of allthe instance members 2fields, methods, properties3 of class A and $ can access all the
members 2e"cept for the priate members3 of class A.
6riate members of a base class do get inherited in a sub7class, but the can not beaccessed b the sub7class.
Also, inheritance is said to create a, 'type of relationship among classes which meanssub7classes are a tpe of base class.
8/13/2019 Net Material
31/45
When ou derie a class from a base class, the deried class will inherit all membersof the base class e"cept constructors
)nheritance in C/
-9, like :aa and contrar to -//, allows onl single class inheritance.
Multiple inheritance of classes is not allowed in -9.\
+he b5ect class defined in the Sstem namespace is implicitl the ultimate base classof all the classes in -9 and the .N)+ framework
Interfaces in -9 can inherit more than one interface So, multiple inheritance ofinterfaces is allowed in -9 similar to :aa.
+o inherit one class from another, use the following snta"8
class Yderied-lassZ 8 Ybase-lassZ
4irtual Method
In ob5ect7oriented programming, a irtual function or irtual method is a function ormethod whose behaior can be oerridden within an inheriting class b a function with thesame signature.
When an instance method declaration includes a irtual modifier, that method is saidto be a irtual method. When no irtual modifier is present, the method is said to be a non7irtual method.
New 0>s &0erride
When used as a modifier, the new keword e"plicitl hides a member inherited from abase class. When ou hide an inherited member, the deried ersion of the member replacesthe base7class ersion.
+he new modifier instructs the compiler to use our implementation instead of thebase class implementation.
public class $ase-H
public int "Gpublic oid Inoke23
H public class Deried- 8 $ase-H
new public oid Inoke23H
8/13/2019 Net Material
32/45
In this e"ample, $ase-.Inoke is hidden b Deried-.Inoke.
We hae an ob5ect of tpe Animal, but it references an ob5ect of tpe Dog. +hus oucan see the base class constructor getting called first followed b the deried classconstructor.
Now we call +alk23 and find that the method that@s e"ecuted is the base class method.When ou consider that the ob5ect was declared to be of the base tpe which in our case isAnimal.
Now when we call Sing23, we find that the deried class method has got called. +his isbecause in the base class the method is prototped as public irtual oid Sing23 and in thederied class we hae oerridden it b using public oerride oid Sing23.
In -9, we need to e"plicitl use the oerride keword
!inall when we call ;reet23 the base class method gets called since the deried classhas not een implemented the method.
#$ample %it&out 'irtual( o'erride and ne% %it& %arning :
using SstemGnamespace McaJ-SharpH
class AH public oid !oo23
H-onsole.Write(ine2KA88!oo23K3G
class 6 : A?@
class +estH
static oid Main2stringTU args3 H A a V new A23G a.!oo23G >> output ++ BA::Foo"$B
$ b V new $23G b.!oo23G >> output ++ BA::Foo"$B
#$ample %it& cross reference and %it&out 'irtual( o'erride and ne% %it& %arning :
using SstemG
8/13/2019 Net Material
33/45
namespace McaJ-SharpH
class AH public oid !oo23
H-onsole.Write(ine2KA88!oo23K3G
class 6 : AH public oid !oo23
H-onsole.Write(ine2K$88!oo23K3G
class +estH static oid Main2stringTU args3 H A aG $ bG
a V new A23G b V new $23G
a.!oo23G >> output ++ BA::Foo"$B b.!oo23G >> output ++ B6::Foo"$B
a V new $23G
a.!oo23G >> output ++ BA::Foo"$B
+here are two problems with this code.
+he output is not reall what we, sa from :aa, e"pected. +he method !oo23 is a non7irtual method. -9 re
8/13/2019 Net Material
34/45
using SstemGnamespace McaJ-SharpH
class A H public 0irtualoid !oo23
H
-onsole.Write(ine2KA88!oo23K3G
class 6 : A H public o0errideoid !oo23
H-onsole.Write(ine2K$88!oo23K3G
class +estH
static oid Main2stringTU args3H A aG $ bG
a V new A23G b V new $23G
a.!oo23G >> output ++ BA::Foo"$B b.!oo23G >> output ++ B6::Foo"$B
a V new $23G a.!oo23G >> output ++ B6::Foo"$B
Method idin# usin# New 3e,word
If a method is not oerriding the deried method, it is hiding it. A hiding method hasto be declared using the newkeword.
When used as a modifier, the new keword e"plicitl hides a member inherited from abase class. When ou hide an inherited member, the deried ersion of the member replaces
the base7class ersion.
#$ample %it& ne% :
using SstemGnamespace McaJ-SharpH
class AH
8/13/2019 Net Material
35/45
public oid !oo23H
-onsole.Write(ine2KA88!oo23K3G
class $ 8 AH
public new oid !oo23H
-onsole.Write(ine2K$88!oo23K3G
class +estH
static oid Main2stringTU args3
H A aG $ bG
a V new A23G
b V new $23G a.!oo23G >> output ++ BA::Foo"$B b.!oo23G >> output ++ B6::Foo"$B
a V new $23G a.!oo23G >> output ++ BA::Foo"$B
Combinin# Method &0erridin# and idin#
Methods of a deried class can both be irtual and at the same time hide the deriedmethod. In order to declare such a method, both kewords irtual and new hae to be used inthe method declaration.
class A H public oid !oo23
H-.W(2LA88!oo3G
class $ 8 A H public 0irtual newoid !oo23
H
-.W(2L$88!oo3G
8/13/2019 Net Material
36/45
A class - can now declare a method !oo23 that either oerrides or hides !oo23 fromclass $8
class - 8 $H public o0errideoid !oo23
H-.W(2L-88!oo3G
&& or public newoid !oo23
H
-.W(2L-88!oo3G
6ase 3e,word
-ase e),or' is use' to &all t$e &onstru&tor o# t$e %ase &lass in in$eritan&e.
*alling constructor %it&out argument
using SstemG
class AH public A23 H -onsole.Write(ine2KAK3G
class $ 8 AH public $23 8 base23 H -onsole.Write(ine2K$K3G
class -on$ase
H static oid Main23
H $ bVnew $23G
*alling constructor %it& argument :
using SstemG
class A
8/13/2019 Net Material
37/45
H public A2int i3 H &&-onsole.Write(ine2K#alue of i in $ase -lass is H>K,i3G
class $ 8 AH public $2int i3 8 base2i3 H -onsole.Write(ine2K#alue of i in Deried -lass is H>K,i3G
class -on$aseArgH static oid Main23 H
$ b V new $2B>3G
Abstract Class
Abstract classes can be simpl defined as incomplete classes.
Abstract classes contain one or more incomplete methods called abstract methods.+he abstract class onl proides the signature or declaration of the abstract methods andleaes the implementation of these methods to deried or sub7classes.
Abstract methods and abstract classes are marked with the abstract keword.
A class inheriting an abstract class and implementing all its abstract methods is calledthe concrete class of the abstract class.
A class that contains at least one abstract method and therefore can neer beinstantiated. Abstract classes are created so that other classes can inherit them andimplement their abstract methods.
abstract class A
Habstract oid callme23G
oid callmetoo23H
-onsole.Write(ine2Lthis is a concrete method3G
class $ 8 AH
8/13/2019 Net Material
38/45
oid callme23H
-onsole.Write(ine2L$s implementation of callme3G
class AbstractDemoH
static oid main2StringTU args3H
$ bVnew $23Gb.callme23Gb.callmetoo23G
Notice that no ob5ects of class A are declared in the program. As mentioned, it is notpossible to instantiate an abstract class Interface
)nterface
-9 does not support multiple inheritance means the classes in -9 cannot hae morethan one superclass.
-9 proides an alternate approach known as interface to support the concept ofmultiple inheritance.
An interface is declared using the interface keword. Interfaces, like abstract classes,can not be instantiated.
An interface can contain a signature of the methods, properties and inde"ers.
An interface is a tpe whose members are all public and abstract b default.
An interface is implemented b a class. A class implementing the interface mustproide the bod for all themembers of the interface.
+o implement an interface, a class uses the same snta" that is used for inheritance. Acolon 8 is used to show that a class is implementing a particular interface.
All the members of an interface are implicitl public and abstract.
An interface cannot contain constant fields, constructors and destructors.
Its member cannot be declared static.
An interface can inherit multiple inheritances.
;eneral !orm to define interface is
8/13/2019 Net Material
39/45
Interface Yinterface nameZ
H
Member declarationsG
)"ample 8 Interface!irst.cs
)"ample demonstrate Interfaces ma also inherit other interfaces
usingSystem;
interfaceIParentInterface
{
voidParentMethod();
}
interfaceIChildInterface : IParentInterface{
voidChildMethod();
}
classInterfaceFirst : IChildInterface
{
staticvoidMain()
{
InterfaceFirst i ne!InterfaceFirst();
i"ChildMethod();
i"ParentMethod();
}
#u$licvoidChildMethod()
{
Console"%rite&ine('Child Method called"');
}
#u$licvoidParentMethod()
{
Console"%rite&ine('Parent Method called"');
}
}
)"ample = 8 Interface+est.cs
)"ample demonstrate an application implementing two interfaces. +he classimplements two interfaces.
usingSystem;
interfaceIddition
{
const dou$le #i *"+,;
intdd();
}
interfaceIMulti#lication
8/13/2019 Net Material
40/45
{
intMul();
}
classCom#ute : Iddition- IMulti#lication
{
int.-y;
#u$licCom#ute(int.- inty)
{
this"..;
this"yy;
}
#u$licintdd()
{
return./y;
}
#u$licintMul()
{
return.0y;
}
}
classInterface1est
{
staticvoidMain(String23 args)
{
Com#ute cne!Com#ute(,4-54);
Console"%rite&ine('Sum is : '/c"dd());
Console"%rite&ine('Multi#lication is : '/c"Mul());
}}
)"ample B 8 Interface+est.cs
)"ample demonstrate Multiple implementation of an interface.
usingSystem;
interfacerea
{
dou$leCom#ute(dou$le.);
}
classS6uare : rea{
#u$licdou$leCom#ute(dou$le.)
{
return.0.;
}
}
classCircle : rea
{
#u$licdou$leCom#ute(dou$le.)
8/13/2019 Net Material
41/45
{
return*"+,0.0.;
}
}
classInterface1est+
{
staticvoidMain()
{
S6uare sne!S6uare();
Circle cne!Circle();
Console"%rite&ine('rea of S6uare is : '/s"Com#ute(+4"7));
Console"%rite&ine('rea of Circle is : '/c"Com#ute(7"87));
}
}
E'plicit )nterface )mplementation
ne of the reason that -9 does not support multiple inheritance is the problem ofname conflict.
+his problem is still there in more than one interface.
!or e".
Interface i H oid disp23G
Interface i= H oid disp23G
-lass c 8 i,i= H public oid disp23H
In aboe situation c.disp23 implement i.disp23 or i=.disp23X
It reports an error.
-9 supports a techni
8/13/2019 Net Material
42/45
{
#u$licvoidI+"9is#()
{
Console"%rite&ine('I+ 9is#lay Method');
}
#u$licvoidI8"9is#()
{
Console"%rite&ine('I8 9is#lay Method');
}
}
classInterface1est8
{
staticvoidMain()
{
C+ c ne!C+();
I+ i (I+) c; casting : o$ect is cast to interface ty#es to
reference their mem$er
i"9is#();
I8 (I8) c; casting
"9is#();
}
}
(ealed Classes
A -lass that cannot be sub7classed is called a sealed class.
6urpose of sealed class is
A class, which restricts inheritance for securit reason is declared, sealed class.
Sealed class is the last class in the hierarch.
Sealed class can be a deried class but can@t be a base class.
A sealed class cannot also be an abstract class. $ecause abstract class has to proide
functionalit and here we are restricting it to inherit.
;eneral !orm issealed class AH
].].
sealed class $ 8 Some-lassH
.....]..
)"ample 8 Demonstration of sealed class. Sealed-lassDemo.cs
usingSystem;
names#aceMca7CShar#
8/13/2019 Net Material
43/45
{
#u$licsealedclassaseClass
{
#u$licvoid9is#lay()
{
Console"%rite&ine('1his is a sealed class !hich can;t $e further
inherited');
}
}
0 #u$lic class 9erived : aseClass
{
this 9erived class can;t inherit aseClass $ecause it is sealed
}0
classSealedClass9emo
{
staticvoidMain(string23 args)
{
aseClass o$ ne!aseClass();
o$"9is#lay();
}
}
}
(ealed Method
When method declaration includes the sealed modifier, the method is said to be asealed method.
Deried class cannot oerride this method.
)"ample = 8 Demonstration of Sealed Method. SealedMethodDemo.cs
usingSystem;
names#aceMca7CShar#
{
8/13/2019 Net Material
44/45
#u$licclassaseClass
{
#u$licvirtualvoid9is#lay()
{
Console"%rite&ine('ase ere !e try again to override dis#lay method
!hich is not #ossi$le and !ill give error');
}
}0
classSealedMethod9emo
{
staticvoidMain(string23 args)
{
9erivedClass o$+ ne!9erivedClass();
o$+"9is#lay();
01hirdClass o$8ne! 1hirdClass();
o$8"9is#lay();0
0aseClass o$8;
o$8 ne! 1hirdClass();
o$8"9is#lay();0
8/13/2019 Net Material
45/45
}
}
}