0% found this document useful (0 votes)
50 views24 pages

Unit 2

Uploaded by

drhypnotoad19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
50 views24 pages

Unit 2

Uploaded by

drhypnotoad19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 24
UNIT Iv _ Cloneable « }. ojects: _ on omparat able ° obje ct |= Custom Indexer Overloacting operotors C# OOPs P stand +f 7 ‘ av oor, for Object ~Oviented atm Procedural programming %s about Writing procedures Or Methods thar Perform eau one the data, while OPPs _ 1s _sbowt « Creating objects thas contatn bath AAA ud paesiasits: ! 0% ~ooPs ts ~ faster cand Rasy: “to ‘execuie - OOPS provide a clear Structure, for fhe ipmegnams: | _ 2 00r S| helps _ to keep” the, C# ‘code > ORY &Dowrt_ Repeat | _Moursett”, cul makes’ the. wae, eanter “+o - malitaiu », riod A. “Class is a Henwplate far “objects | 3.and on Object is an fustance | Of Oo clay — tohen the imdividval obfect is create i ey Mhert- the at the voutables Land ~ methods _ “from the Um. os A Nam amespace Fu CH fs a covlection of Clases. Te provides a structere to keep one class mame _Seperake from | uscther” “clas na i Car Ouspus ¢ red wed ved String Clot = “red” Car myOby = new ‘Car Cruel “Writeline Cruy 5 MW Field “my Objd = new Cavs mew Cart)5 Static void Main ( string] orgs ) dlRésia~ [aie : poulie. Siving model 5 CH Feld aes ee] Cay Fordico _, Gwole. Uridine Fordioes nese) Suspar t ® Mastan igs! a Mustang Encapsuladfou ¢ ~ Encapsulation ts’ an OOPs Concept that ALLows programmers fo wrap data and | Code srippets Unside an enclosure ov _ Suge entity. we Ry | using the encapsuiteHou We Can hide the members _ of one Class frome auch er elm. * T+ slows only relevant . Available and visible ouside” and ‘thax foo ‘only to specific menabers. _Encapsulviow fs _Tmplemented by us “using accens specifters . Accem Spedtier is used -for deputy Hie -visibili “aul recent bility of the cles membey in Ge. e# toutain the folesieg Accens spe © Public z - e Private” et © Protected oe Internal Accor Speciffers define - 4he_ visibility ‘fe the claw aud its’ valde. _ fouctens ublic & The. public keyus word allows Hs members sto be visible frome the project. y has the ouyehey tuuide access SP “least ity restricHou. ae members can ony be anibiity allows re member to be accemeds “aud | Objects “iu the ure | anewbly. ! “Tuhevitance $ Tnheritance is q proton In which dne -object acquires “ol the | properties and behaviowy | of its “poseust object sustomacticaty « © Derived Clay C child) ® Bose Class C pavert) _ Systems claw Animal. using pout claw “Test Inheritance £ static void. Hata (thio apd Tf pe dol wont imnerit froma Clam _ Keyword | 2 Not -_ Support “multiple inheritance _ “the some thing Can be done vs a nities. i “(© single) || CN erommple , “| exemple 5 | eramaley chy a’ "cha f ‘Cheat PETE a en one class fs derived ea | Cétaas BAL ee Clan BIA } - = ae < —clayCiaf | a t S clays DAY St 7 ‘ cic UUM OES Code ¢ a : — class Program £ 7 ‘ void priv C tut fj iur jf). t-- void priat C string 45 string b) { - static void Motu ( String 2) args) Progvom prog = new Peayeara Cs preg. privet S56 )3 preg + py iMt("Hello”, wy World") 5 Cowrsle « Read key() Polymorphism t T+ means one with Many forms. TH is bascicutly divided fnte too pasds ¢ 1. Compile—Hime felymor phism. 2. Ron Hime _folynioyphisna . 4. Stave, or Compile Time Poly morphism : Metnod overloading fs ane ef the way im _ uslich compile ~ time palyme' phism } : is) achieved. °° 2. Dynamic Polyrasr pita or yr Routine Tt is known as Compile-time poly. b/e Polynioyp Use : 7 Tr occur when both meiteoc name oucl_ method, atyibuse have, the seme Fmjame od +ype- r Method ovemidiy is. Qchive Ustn, jmheritouce | widen Cause Rowdi a Re decisiow to Ton a meted [agate __doring —Yentime. THis | use to implement Abstractot the method cating clecision Is mace Gt the me of, Compiling. “TH fs achieved by Keeping the method name | same bet pasing difterena* set 4 pordinele TRe system first checks the pasamesr wsecl aud based on the set Porameter ft ‘decid& to cate the, appropriate | metrod- ~ clos | Avital a publicy void auimatSound () 4 ; vtrtvok . _: . bm ae cw oven Clay Pig if mat { pootic ‘void ouimalSeoud ( ) } {--:} Cle * Dog + ait { public “void auimal sooud () to} yeh presse elaw Prograw Lo static Void maiu ( string C7 args) { : “Avimal myAuinnel = Hew Auumel 0) Pratinah may a = mew Fg; fatima hay Dae = wew Dog Us “ay Prato ascii at Sooud ()5 a Woy Pig -cxsinal Sood 0)5 niybog - aimatboord td; 7 - “ a The ouimal makes a Soon Thee plg says wee wee The, dog Says t bow bow Quspur 3 Abstrociion is one atthe major priucipie, of OoPs. prstractou allows the programmer to cletaile Abstraction : Asc display ouly “the neceman Pye ee worl wuile hidiug the other. pstroctou 78 Achived iu CH by co . Abstact ~Clas cud ‘interbace Abstract Clesias Th is a vesticted class nat cannot be Used fo “create objects. ~ Fr Abstract method: Tt cau only be used sm au abstract class gud ff does uot have a body - The bedy provided by The derived claw. = fAn Abstract clas Can have. bok abstract cd yegular methods Fe To access abstract claw sit must be inherited from austher “Ristocd Clas end Mead are, sed Fe achive, Security . Code t Wrteface TAntmat { yotd — onatmat, Soonet (4 t Sto Pig yTAuimat £ © Vo onimat Soon) ¢ Console wortteling (uve wee ")5 ae ela Py ag yant < Statte void Maiy (Shring () ogy) Pig my Pig = new Pig: bis Ng + QuimalSovud ©) 5 ‘ t Ouupurs wee wee. Lmemory se thet this memory Cou be Yeusect opject Lifetime _in sNet_ framework Object Lifetime s the tme when a block of dnennny is allocated to the object duty some proces of execetion and ayeu Weck of memory “fs releared when te precess enc. Re Qnce the object Cs allocated with memor He ts necessary to yeleaae thas memory go what fH fs vced for further procening, oiherwise Tt would wesw in memory leaks. We have a clam in .NeT hab relewes memory atlomeaticatty for us whe the abjed ts mo longer” useck When the ‘new? operaley fs Used Yo create an abject» memory ts faken from the snamaged heap for the objec and the manage et heap fs more ~hau just a _varedom chow merry actemed by the CLR When the objeck is no longey used Ane th is de~ allotted from Graxbage Collector's The key pillay ‘of the «NET framework is Whe curtomatte garbage collection that Manages memory for ott + NET appl fvacbong, is Generations ? “The managed hea has. —l_sthree_logfeal segment waich ae also known Os “Ge nerartons mside the _ managed hy v4 cning Gehind The genrai@oiey BE fae fe cee pera he fo eg a When we create any object in CH, CLR allocate, memory fer the object from heah. |” This process fe yepeated for each newly — creased object , but there fs a limitation jo everything , Memory fs net onlimited and We need 4o clean some used space im order to make Toom for new object —S Usually the newly Creaked ove _: Shorter Wife Compared to old__objects. Garbage callectfon manages Allocadiou anol Teclaining memory + GC makes a trip to athe heap orc coliecks alt objects that are mo longer used by he applfeatton aurel fhe makes then -free from _ Theory « = Newer w objects are bsvally have Sfmilan likelime and Managed Heap is an area of -the virtual memory Available +o Ow procers +hat the CER uses for, Storing ivstance of reference _ ype (object) that we create. a T+ always contain addres to the ne free location where objec will be allocated tasked - And garbage uns ae __generatton _ first. ane Generatfon 4 ¢ an ering generation 1 where objed are short Vived but longer then the ger 0 objed « His _a__ bridge bekween gerd aud geud, yo the abject fre m either Null or fe points to an objeu ryhe_ monaged heap. he “rools the GC Creates a 979] objets | watch ave Unked +o “Genevatfou 2+ enerayfou Cor the long | lived objects for exauple singleton “objects creaked iu the Web APT: The, object which ave wot ia the grep » “bur ove iu the managed heap ave essehiially 7 10. be collected Large Object Heap i For performance rea eer ‘improvemesks lange objects Ore Wot kept +hree generatiew - in any Of the _ Lage object are kept ina _Seperase_ location Catledt LOH 4 Sometime tt és, also Calleol as generatiou 3 © Ofjed that ave greader th 85,000 bys are Teas number ts determing by a Jeintice - Tre GC hen calls memary opying -fod tion 7 _Compack “Object gabiich_ _are ne_pointer to the next locatfou: ~_avaitable memory Hier the very first Qavbage eallecitou Guc mentary Compe procem is dove 5 the ciscuucmuueRs ES memory tocadtows ‘od the: object het > 7 GC proces fs markedas get. | trst GC, the entire managed | constdey as gerd: survive qne Before the heap ts ] then the second GC happer Goheakever objet | from gent survived the collech’ou News ae use heats When the’ object. oses an ~ unmanaged resources Uke | database. or file menibulation 5 jlewed reanwelly ana th ~gonneckons the G2) Sign in "our Code 4o destroy will a manked a gene wich Sb Fre object and this clistructoy_ 5G 2 [ss] nto a finalize method + This ts known jut ke ) OE | [rere 1] 2% finblization prrocen - nn Root) + 5 [obs = Lae ob} E bie ISS op fy Je se oti obi c objD eel ObsB |v fate fous | [owe Dfera [et ch [esa] jour |] Applicatfou Reab o Every Ape has set q Roots + foot Hewtify Sloraye Uecation B) © TIT awa Cek maietaln the Tet of active Yee oud provide. € A) ue a Cam Yedaine the objects memury in gle mesiod Wu be Used Component oY User defined claw Libvary- A Component fs retursable piece ok code oud is in tne -form of DLLC Dye © Link “web appitcetion.— Once 4 tomponerk Spgs 1S cone from cay other prg- loug- Assemblies will provide louguage Interoperability. au a Te cveate component in enet we | iby Use coy ferpleds End user will never inteyack with DUL_oY component Directly+ Alwayy en user will interac with some application Gmd__Hre «will Intevac: with wormporent oy DLL sing, System 3 namespace. MyClassLibyary pubiic clas ClsAvithmatic, public. component nt Numi, Nuw2, Results Program : fut PNumd £ set f ue PNow2 £ Set{ Numr = Value usin names £ Se Pe Zi Ouspur * m ClasLtbyar pace Corvole A pp i Consume DLL Oy Add C5 one ~_ trex Laces - Compiled DLLs or ibe rnwltp ima a portable _ exeurtable $e “type: vali or oi er exe Clawsen single Exes” Bye Called Assemblfer. An Assembly cau Goutain ety number ols. = other Yeyovurces + modules ay Wel ay Console + Write Lint Window forms tn C# Windows forms fs a Graphical User Thierface CUUT) claw Iibyany _voldich _ is bundled im + Net framework Tis main purpose is +o provide an easiey jwitrface +o develop the application i desktop ytarlet , PCs. Th fs “also termed a, win forms. The applications wlich are ceveboped y sing Window forms or Winforms eu kuown Os Hee Windows forms | Applitation - thet uns ow the _derttop | Comput + pie win form con be used _onty “to develop tue twirdows forms. Prpplication wot web application . i Winforms application con Coutain tHe a ereut type a counols ike labels ‘Lint bom? 7 Tootiip rete decom ble The user will Quer the re qurii Teedadtiots oud then will by the e user, ) ekanigle af a Simple indosn _ click “the Cloneatle objects Cloning is a proces of. treading a mew | Suse rent on existing Objecke _ We can” achieve Cloning wsing tuo cHehwiques tela (ond “then capying the non- aie. aie Ake uurrent objed to ane nee” object rf the field is a valve Aype » a bit by tH | copy ol the field is performed- J ee #ela a reference types the wedterence is Copied but the Yelerred objed is not , therefore the original (oid objec) Stodent t Teacher teacher | tut age=20 2 Deep Copy ? Deep copy Ts eang aes | bject Gud ther topyin static _fietds_ | the wurvent a so the new object. _iutage=20 | | | av ageete [+ Clomed |} Teacher. teacher] Object oud its clone refer _“K so same objeck __ Shallow copy is alone by the objet Metuocd — Mernuberwise —____feavher, (e “provide an Ttomparable srk “Ths; 4 interface _ provides _alifjerent _ types of ar ctype=specijtc comparison methods usktch | means G@ Value’ type oy a. ¢ iaplement its * n_ Compare ee a theo CaYreict Metro: the compiley clogs wot Kucw OM bovis to sort. sein compart: Will throw — conipiléy dive Compiler get confused Br rah Ps they oo Bytances | wer as the ‘Tmplementing . Tompoxable Tnierhace_ __Tegqurres t “a _metiiod Compare ToC ) wolate au object aud TeHurs aK im Heger. ° The fnwming objeck Fs J os the claw “ype cud ‘store t [ti veturn dt, i] Pre current a. reknn 0, tne the aurrent _imstance’s roper is equat to the Hempora vostalle’s property. iustance Le reperty fs greaky thaw fhe -Houporar, __“vausiablels proper the Current it _pasperty_ les thaw he ony veutgilels cay C# Collectons Im Ca + conecton represents group of objects + By the help © Collec tion . 7 we can perform vavidous —opoxadions on objects such a 3 estore Object e update object © delete object © rerieve object © seauch object , aud © sort object In sert+ . att the olata structure work ) cam be perfermed by C# collectfons. We com store objects in array or — collecten. Collection hax advaactage over array - Array has size Pmt but ejects Stored in Collector can grow or Shrink aly namically. y Type of Collectons im C# i There are 8S ways fo Work with Collection . The. 3 “namepace are + memepace. has pellouing clyes © Apvay Ust —* Blocking Gl is System GollecHons Generic clas 3 “the Systems Callections. Generic. snamespace has following claves > 7 0 List eo Sorted Set o Stack 0 DictHonary e Queve © Sorted Dictonary 7 @ Linked list © Sorted USt © Hash Set 7 7 2. System. Collections | Tene Clases suggested wow to cGeneric cl. he Syst cf ove eStock — oe Queve 3. System + CollecHow « Concurrent Cl 2 T+ provide clas for _thred-se oper Hom - Mow vuudei ple thread i | ot creak, problem fer accent collection items Advance Class _Constviction cH Tndexer” iF sancti ale te Syrtax ¢ pre peux d meRTS An Inder’ allows an instance af q} Laccess_modi fier] [vetuin type] this Lergument Fst) elm oy Struct to be indexes ah] © Brroy + TL the _vser will aleline Bn __‘ndexey for a cla» rthen the clay. wil behave like a yirdoak as Array _ ace operator fe (EJ) 9 _ Used FO acces the instance ef ad chy Whe uses BH Inder TL ee ek ee SE A_user Can rehieve Or Set the Indexed value ud Heouct peieting ou _insternce. or 4 +ype member. There are uo. types | oh “Tha exers ies one Dimensional “Indexet dnd Muti | __ Dimentonal Trelerer - __Tnaexers* can be overléadedt They Pre cliftereut from —_Propertign __Tradevers. can aso be declared sft = “alti ple, Paamelers tnd each poxamery “wou be different Type: Tt is wet mecessary that the imderes, have to be integers. : CH cdlows indexes to be of © for tau TH enables Object Jo be indexed access specifier clasNome ¢ The can Cherator overloading gives the 8 0 use the same operator fo do_ Vvasifous CH Operator Overloading Conce ft of also te appl operations - It provide additonat capabilities to, Ge Sperajoys chen they _ are applied -to overloading a-fouctou a f =} class Cateulator { liecl to _ operators. User - deinect clcta types + Tt ena tle to make user-deline incplementations of vaufous operation cote be ov escloades « the operanel § Gre 4 use a claw. s where one oY bette egined | ony the predexinedt ser ao CHE Operators An operatey cau be overloaded by defied The declaved 6 vs the _ operator keyword YOY P v “fi a? Symax: I cocke. a Otome yo fH. “the operasor is Operatay. Operator symbe) a using System 5 moméspace Calculator { fs uplic fret umber d y nueber 2 3. __pblic. Calculator Cint numa, fut num?) _ 5 “public static Colewlotor ae -(Coltaior cz) = Cd muniberd Cds nevaber 25 public void Prive 4 __ Comolent wurikline ve (Number d=”: "+ mumberd -Wrifeline( Number 2= ” 4 now ber2) > HC void Main (Shing (J args) £ aleulector Cale nes Caetaer( 8 -25); hold a " “0 Provide a good way fo encapsulate the CH Dategates A delegate fs an object which refers to 0. method or we com Sey fF eG xeperence type Vartia ble “thot Coun referent > the 7 fo the Meivods | Delegates sp PEO ifbvory | claw fu He pelegates ave Molly usecl_ in inplemendig que Colb~back metaeds aud events. __Cheived. Hypeioere nore Metiods Can be i gone noml spe ele Delegate type cau be cleclared. my | the” clelegate keyword. “we Uitk oma Butow | Syntax? sa a doled program woutel cat a on a Jorn 5 + spedlic metuad» In sinaple words; it is | Cmodifter] | delegate Lretau type] [delegate rome) a type that represents reperences fo _______( tparomeler—list 1 )5 metiods whi a poctiutax’ poxameter: : Once a delegate is devaued 5 delegate imstance will teler aud cae. “tose metiods “Wiese rekon ype dud onametey Uist motches wit the type uel then & the metwod. a_progran fer erection when FH Fs nebleae 7 Tinporleut > pobeis Code? (vse te_Deleasic) usmg_ Systert using Se _Geekforgeeks (i eenaaemeoee After declaring a el ae a 1 detegate object fs created with 4he. het & , new keyword. Once a delegate is mstauciattd + a mettiod Cate made cto Ae delegate fs pass. 7 the, delegate to “hat “meted. Cla GOREN a Pato wi a ot a pie silegale Syntax + public void sum( futa 5 i [aeleg are name] [instamename] = hew [delegate oan CemotervrtteLine ("(fo}H144)= Coo Hing -| mefued- name) ; THis an exqenmieu of the | Kormal clelegate « T+ hetp Hee user to peiut ruore thou one Metod ih q single “Catt - : : _Mutiicauting of 8 Delegate _ public state voi = Geeks by = ‘addnum delobj re Abl—obj 2 = new Geek); pists Xe = hw sano ob ne opelegais are combined cul When Ue cat a clelegate then a lomplee list &4 metund ts called, oan meiuods ore cauled im FIeO. o 4 oy +=!’ are use to add Mmetuod. el oyL=) ave use to Temove meted: C# Event Fyents are user acHons such as key pres, Clicks, moure Movements C1 OY SOME OCCUIT ER! fons. Such ax system generateck votifi Fyents are Cletegate that Can onl from within the class (or derived claw) or Struct where Wey are declawed ( Fae publisher clam), a Speciak kind of multicast a, be Invoked AN Neation need to repond 40 events when they occur. for example » interrupt. Eveut ave used for nity preven, Communication Eveut 7s an encapsulated clelegate CH and «NET doth Support the event with the delegates. Delegate dud Eveut ty are 4ighily coupled for dispatching he _ events and events handiis requted the implementatfon’: othe clefeg ats The sendy event “Cay fs Known as the ane the welver Clavs ov haneliin 1 publisher : ae 4 event is Kvown On a § d key point about events + eqn C# event handler will fake the two powometers Gs input and ‘return the void - The -first povameter Ts trewy ay Source © Fvent can Contain many Subscribers © Generally » we use Event for the single usey actou like Clicking on the butOK Will dedde when we have fo valse the Event; and the — Subsovber will detrmine what response we have fo give © The publisher To declme an event fnsfde a Claw, fis % ali ,we must declare clelegate type Went then, declave the event usi event keyword. Code: Using System namespace SampleApp v . pustic dele gate sing Mypel ( string str) 5 class EventProgram { event Mybel _MyEvent 5 public Event Progvara Of -thisemyEvent += new MyDe| (thi-Welame : a User) 5 +} Ublic. String WeltomeUser (string axoriome) { return "Welcome ” + username 5 state votd Maku (stringl] args) { EventProgam obj 1=hew Eventfrograu(); String Fesult = 0b;4-M Event (“Abhishek”): rp Console. writeLing ( vesul+) 5 } Oulput So “Welcome Abhishek. ciscuusemuuaselnS

You might also like