Вы находитесь на странице: 1из 45

Windows DNA

Windows DNA is short for Windows Distributed interNet Applications Architecture. 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 the Internet to work together. Windows DNA is a e olution 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 include Acti e0, D,namic 1+M( 2D1+M(3 and -.M. Microsoft no longer uses this term.

Microsoft .NET :
.N)+ is a platform that pro ides a standardi4ed set of ser ices.

Features :

Its 5ust like Windows, e"cept distributed o er the Internet. Its a powerful and robust software de elopment technolog,

It e"ports a common interface so that its programs can be run on an, s,stem that supports .N)+. 6ro ides a multi7language de elopment platform, so ,ou can work in the programming language ,ou prefer. It pro ides the securit, ad ancements, management tools, and updates ,ou need to build, test, and deplo, highl, reliable and secure software.

.NET Framework
+he .N)+ !ramework is an integral Windows component that supports building and running the ne"t generation of applications and 0M( Web ser ices. +he .N)+ !ramework is designed to fulfill the following ob5ecti es8 Appl, common skills across a ariet, of de ices, application t,pes, and programming tasks Integrate with other tools and technologies to build the right solution with less work $uild compelling applications faster +he .N)+ !ramework has two main components8

Common

anguage !untime

.N)+ Framework Class ibrar,.

$, pro iding, a comprehensi e and consistent programming model and a common set of A6Is, the .N)+ !ramework helps to build applications that work the wa, ,ou want, in the programming language ,ou prefer, across software, ser ices, and de ices.

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 la,er that resides abo e the .S and handles the e"ecution of all

the .N)+ applications. 6rogram doesnt directl, communicate with the .S but go through the -(*.

-(* is an agent that manages code at e"ecution time, pro iding core ser ices such as memor, management, thread management, and remoting, also enforcing strict t,pe safet, and other forms of code accurac, that promote securit, and robustness. In fact, the concept of code management is a fundamental principle of the runtime.

.NET Application Common Language Runtime (CLR) Windows OS



At runtime, the -(* has no idea which programming language the de eloper used for the source code. +his means that ,ou ma, de elop ,our code in an, programming language ,ou desire as long as the compiler ,ou use to compile ,our code targets the -(*. Microsoft is creating se eral language compilers that target the runtime8 -// with managed e"tensions, -9, #isual $asic.N)+, :Script, :a a, and an intermediate language 2I(3 Assembler. In addition to Microsoft, other companies are also creating compilers that produce code that targets the -(* like Alice, A6(, -.$.(, -omponent 6ascal, )iffel, !ortran, 1askell, Mercur,, M(, Mondrian,.beron, 6erl, 6,thon, *6;, Scheme, and Smalltalk.

As the figure shows, ,ou can create source code files using an, programming language that supports the -(*. +hen, use the corresponding compiler to check s,nta" and anal,4e the source code. +he result is a managed module. A managed module is a standard Windows portable e"ecutable 26)3 file that re<uires the -(* to e"ecute. In the future, other operating s,stems ma, use the 6) file format as well.

Mana#ed Code and %nMana#ed Code


-ode that targets the runtime is known as managed code. +he code, which is de eloped in .N)+ framework, is known as managed code. +his code is directl, e"ecuted b, -(* with help of managed code e"ecution. An, language that is written in .N)+ !ramework is managed code. -ode that does not target the runtime is known as unmanaged code. In short, the code, which is de eloped outside .N)+, !ramework is known as unmanaged code. Applications that do not run under the control of the -(* are said to be unmanaged, such as -//, #$, #-//, AS6 and -.M. In short, application made before #isual Studio .N)+ =>>=. ?nmanaged code is e"ecuted with help of wrapper classes. Wrapper classes are of two t,pes8 CCW "C&M Callable Wrapper$ and !CW "!untime Callable Wrapper$.

Mana#ed code e'ecution process

Source Code
Nati e Compile!

MSIL Code
Language #ndependent wit$in .NET %!amewo!&

Native Code
"#T ("ust in Time) Compile!

CPU

Output

Difference between mana#ed code and unmana#ed code :

Managed code is created b, b.net and c9 compilers. +his t,pe 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 s,stem. +he -(* cannot instruct the code.

M() "Microsoft )ntermediate an#ua#e$ Code


When compiling .Net compliant 6rogram 2Managed -ode3, the source code does not get con erted into the e"ecutable binar, code, but the compiler translates it into intermediate code 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, con erted to nati e code. At the time of program e"ecution, this MSI( 2intermediate code3 is con erted to binar, e"ecutable code 2Nati e -ode3. -ross language relationships are possible as the MSI( code is similar for each .Net language.

When a compiler produces MSI(, it also produces metadata. Metadata describes the t,pes in ,our code, including the definition of each t,pe, the signatures of each t,pe@s members, the members 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, which accommodates MSI( or nati e code as well as metadata, enables the operating s,stem to recogni4e 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 compilation 2*)T3, also known as d,namic translation. +his is a techni<ue for impro ing the runtime performance of a computer program. When our I( compiled code needs to be e"ecuted, the -(* in okes the :I+ compiler, which compile the I( code to nati e e"ecutable code 2.e"e or .dll3 that is designed for the specific machine and .S. :I+ -ompiler is different from traditional compilers. It compiles the I( to nati e code onl, when desired. ).g. when a function is called, the I( of the function@s bod, is con erted to nati e code 2just in time). So, the part of code that is not used b, that particular run is ne er con erted to nati e code. If some I( code is con erted to nati e code, then the ne"t time it@s needed, the -(* reuses the same 2alread, compiled3 cop, without re7compiling. So, if a program runs for some time, then it won@t ha e an, 5ust7in7time performance

Code in any .NET Language

Language Compiler compile time

MSIL Code

Just in Time Compiler run time

Executable Native Code

Microsoft stated that -9 and .Net are not competing with languages like -// in efficienc, and speed of e"ecution, :I+ers can make ,our code e en faster than -// code in some cases when the program is run o er an e"tended period of time like web7ser ers. 1owe er, if managed code calls platform7specific nati e A6Is or a platform7specific class librar,, it will run onl, on that operating s,stem.

Framework Class ibrar, "FC $


+he .N)+ !ramework class librar, is a collection of reusable t,pes that tightl, integrate with the common language runtime. !-( contains thousands of classes to pro ide access to Windows A6I and common functions like String Manipulation, -ommon Data Structures, I., Streams, +hreads, Securit,, Network 6rogramming, Windows 6rogramming, Web 6rogramming, Data Access, etc. It is simpl, the largest standard librar, e er shipped with any de elopment en ironment or programming language. +his not onl, makes the .N)+ !ramework t,pes eas, to use, but also reduces the time associated with learning new features of the .N)+ !ramework. +he best part of this librar, is the, follow e"tremel, efficient .. design patterns which make their access and use er, simple and predictable. .ne can use the classes in !-( in program 5ust as uses an, other class. Aou can e en appl, inheritance and pol,morphism to these classes

Common T,pe (,stem "CT($

-+S is a set of standards. +he -+S defines how t,pes are declared, used, and managed in the runtime. +,pes are the mechanism b, which code written in one programming language can talk to code written in a different programming language. -+S defines the basic data t,pes that I( understands. )ach .Net compliant language should map its data t,pes to these standard data t,pes. +his makes it possible for the = languages to communicate with each other b, passing&recei ing parameters to and from each other. !or e"ample, -+S defines a t,pe, IntB=, an integral data t,pe of B= bits 2C b,tes3 which is mapped b, -9 through int and #$.Net through its Integer data t,pe. D+he common t,pe s,stem supports two general categories of t,pes, each of which is further di ided into subcategories8

#alue +,pe

*eference +,pe Value Type

#alue t,pes directl, contain their data, and instances of alue.

#alue t,pes can be built7in, user7defined, or enumerations. Reference Type *eference t,pes store a reference to the alue@s memor, address, and are allocated on the heap. *eference t,pes can be self7describing t,pes, pointer t,pes, or interface t,pes. +he t,pe of a reference t,pe can be determined from alues of self7describing t,pes. Self7describing t,pes are further split into arra,s and class t,pes. +he class t,pes are user7defined classes, bo"ed alue t,pes, and delegates. All t,pes deri e from the S,stem..b5ect base t,pe.

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 <ualif, as a .Net -ompliant (anguage. All the rules that appl, to the common t,pe s,stem appl, to the -(S. -.M allows ob5ects created in different languages to communicate with one another. +he -(* goes further. It integrates all languages to let ob5ects created in one language be treated as e<ual citi4ens b, code written in a completel, different language. +o make this possible, the -(* defines a standard beha ior for t,pes and pro ides a common e"ecution en ironment. (anguage integration is a fantastic goal, of course, but the truth of the matter is that programming languages are er, different from one another. !or e"ample, some languages lack features commonl, used in other languages8

case7sensiti it, unsigned integers

operator o erloading methods that support a ariable number of parameters

If ,ou intend to create t,pes that are easil, accessible from other programming languages, then it is important that ,ou use onl, features of ,our programming language that are guaranteed to be a ailable in all other languages. Microsoft has defined a common language specification 2-(S3 that details for compiler endors the minimum set of features that their compilers 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, for ,our application. )ach time a new ob5ect is created, the common language runtime allocates memor, for the ob5ect from the managed heap. As long as address space is a ailable in the managed heap, the runtime continues to allocate space for new ob5ects. 1owe er, memor, is not infinite so garbage collector has to checks for ob5ects in the managed heap that are no longer being used b, the application and performs the necessar, operations to reclaim their memor,. If no more memor, is a ailable for the heap, then the new operator throws an .ut.fMemor,)"ception. When the garbage collector triggered, it makes the assumption that all ob5ects in the heap are garbage. It reclaims the memor, that is occupied b, dead ob5ects. +he reclaiming process compacts li e ob5ects so that the, are mo ed together, and the dead space is remo ed, thereb, making the heap smaller. +his ensures that ob5ects that are allocated together sta, together on the managed heap, to preser e their localit,. A garbage collection has the following phases8

A marking phase that finds and creates a list of all li e 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 ser ices that the common language runtime pro ides during Managed )"ecution.

+he 6rocess includes Allocation of Memor, *elease the Memor,

Allocating Memory
When a process is initiali4ed, the runtime reser es a contiguous region of address space for the process. +his reser ed address space is called the managed heap. +he heap also maintains a pointer to the address. +his pointer indicates where the ne"t ob5ect is to be allocated within the heap.

Abo e fig shows a managed heap consisting of three ob5ects8 A, $, and -. +he ne"t ob5ect to be allocated will be placed where Ne"t .b5ect 6ointer points that is immediatel, after ob5ect -. When an application creates the first reference t,pe, memor, is allocated for the t,pe at the base address of the managed heap. When the application creates the ne"t ob5ect, the garbage collector allocates memor, for it in the address space immediatel, following the first ob5ect. As long as address space is a ailable, the garbage collector continues to allocate space for new ob5ects in this manner. Allocating memor, from the managed heap is faster than unmanaged memor, allocation. In managed heap new ob5ects that are allocated consecuti el, are stored contiguousl, in the managed heap, an application can access the ob5ects er, <uickl,.

!eleasin# Memor,
When the garbage collector performs a collection, it releases the memor, for ob5ects that are no longer being used b, the application. It determines which ob5ects are no longer being used b, e"amining the applicationEs root. +he garbage collector has access to the list of acti e roots. +he garbage collector considers unreachable ob5ects garbage and will release the memor, allocated for them. During a collection, the garbage collector e"amines the managed heap, looking for the blocks of address space occupied b, unreachable ob5ects. As it finds unreachable ob5ect, it uses a memor,7cop,ing function to compact the reachable ob5ects in memor,, freeing up the blocks of address spaces allocated to unreachable ob5ects. .nce the memor, for the reachable ob5ects has been compacted, the garbage collector makes the necessar, pointer corrections so that the application@s roots point to the ob5ects in their new locations. It also positions the managed heap@s pointer after the last reachable ob5ect.

!eleasin# Memor, for %nmana#ed !esources


?nmanaged resources re<uire e"plicit cleanup. +he most common t,pe of unmanaged resource is an ob5ect that wraps an operating s,stem resource, such as a file handle, window handle, or network connection. When ,ou create an ob5ect that encapsulates an unmanaged resource, it is recommended that ,ou pro ide the necessar, code to clean up the unmanaged resource in a public Dispose method. $, pro iding a Dispose method, ,ou enable users of ,our ob5ect to e"plicitl, free its memor,

when the, are finished with the ob5ect.

.NET Framework
+he .Net !ramework is the combination of la,ers of -(*, !-(, Data and 0M( -lasses and our Windows, Web applications and Web Ser ices. A diagram of the .Net !ramework is presented below for better understanding.

.istor, of C/

.riginated b, Microsoft as a response to :a a Initial public release in =>>> (ead designers8 Anders 1e5lsberg, Scott Wiltamuth -9 standardi4ed ia )-MA and IS. 1owe er, Microsoft retains architectural control

Features

?nified ob5ect s,stem ) er,thing t,pe is an ob5ect. Single inheritance Interfaces Specif, methods F interfaces, but no implementation. Structs A restricted, lightweight 2efficient3 t,pe. Delegates )"pressi e t,pesafe function pointer. ?seful for strateg, and obser er design patterns. 6reprocessor Directi es

!ules

-ase7sensiti e Whites pace has no meaning Semicolons are used to terminate statements 2G3 -url, braces HI enclose code blocks

First C/ Application
using S,stemG namespace McaJ-Sharp H class 1elloWorld H static oid Main23 H -onsole.Write(ine2K1ello WorldK3G I I I

OutPut : Hello World


Error namespace McaJ-Sharp H class 1elloWorld H static oid Main23 H -onsole.Write(ine2K1ello WorldK3G I I I

(a0in#1 Compilin# and E'ecutin# the 2ro#ram

Sa e the file with e"tension L.csM .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 recei ed the Lcommand not foundM error, the command interpreter couldnt locate the csc.e"e application. +o remed, this, ,ou need to make the change to a 6ath en ironment ariable.

G-8D6rogram !ilesDMicrosoft #isual Studio NDSDOD =.>D$in G-8DWINN+DMicrosoft.N)+D!rameworkD =.>.J>P=P G-8D6rogram !ilesDMicrosoft #isual Studio ND#-Dbin G-8D6rogram !ilesD-ommon !ilesDMicrosoft SharedD#SADN.>D#sa)n G

Namespace

+he second line of code that ,ou see in the demo is the definition of a namespace named McaJ-Sharp. A Namespace is simpl, a con enient wa, of logical collection of related classes in -9. +he namespace ma, contain classes, e ents, e"ceptions, delegates and e en other namespaces !or )". It is er, much possible that our -onnection -lass in DataActi it, conflicts with the -onnection -lass of InternetActi it,. +o a oid this, these classes are made part of their respecti e namespace. So the full, <ualified name of these classes will be DataActi it,.-onnection and InternetActi it,.-onnection -9 does not allow two classes with the same name to be used in a program, the sole purpose of using namespaces is to pre ent name conflicts. +he -9 namespaces ha e N. ph,sical mapping as is the case in :a a. -lasses with same namespace can be in different folders.

usin# 3e,word

+he first line of our program uses LusingM ke,word, this ke,word allows to use the classes of the namespace defined with the ke,word. !or e". using S,stem. $, doing this one can access all the classes defined in the S,stem namespace like -onsole class in our program. using allows ,ou to access the classes in the referenced namespace onl, and not in its internal&child namespaces. 1ence ,ou ma, need to write using S,stem.-ollection

The class 3e,word

All -9 programs contain at least one class. -lasses are combination of data and methods.

-lasses in -9 are defined using the class ke,word followed b, the name of class. In our e"ample its class 1elloWorld

The Main method

) er, -9 application must define a Main method in one of its classes.

+he Main method is the entr, point of program. i.e. -9 program starts its e"ecution from the first line of Main method and terminates with the termination of Main. +he Main method is designated as static as it will be called b, the -ommon (anguage

*untime 2-(*3 without making an, ob5ect of our 1elloWorld -lass.

+he method is also declared oid as it does not return an,thing.

(,stem.Console.Write ine Method


S,stem Q S,stem 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 S,stem namespace. +his method takes a string 2enclosed in double <uotes3 as its parameter and prints it on the -onsole window.

Comments

Single line comment Q 2&3 Multiple line comment Q 2&R 77777 R&3 Document -omment Q 2&&&3

using S,stemG namespace McaJ-Sharp H class 1elloWorldS H static oid Main2StringTU args3 H -onsole.Write(ine2L1ello World K / argsT>U3G I I I

Data T,pes
Numeric Data +,pes

?nsigned 2positi e3 b,te, ushort, uint, ulong Signed 2positi e or negati e3 short, int, long, float, decimal, double Select the smallest t,pe that will hold the re<uired range of numbers Non7Numeric +,pes8 char and bool

char 1olds 5ust a single character -an hold8 Simple character 2EA3 ?nicode character 2uD>>CS3 )scape character 2EDn3 bool 1olds true or false in one b,te

Declarin# ocal 4ariable

namespace McaJ-Sharp H class AdditionDemo H static oid Main23 H int a,ansG &&declare multiple ariables. aVS>G int bV=>G &&declare and initiali4ed ans V a / bG S,stem.-onsole.Write(ine2K+he addition of two numbers8K/ans3G I I I

OutPut : The Addition of two numbers : 30


using S,stemG namespace McaJ-Sharp H class ;reet H static oid Main2StringTU args3 H String nameG -onsole.Write(ine2K)nter Aour Name 8 K3G name V -onsole.*ead(ine23G -onsole.Write(ine2K1iWW H>I 1ow are ,ouXK, name3G &&-onsole.Write(ine2L1iWW M / name /M 1ow are ,ouXM3G -onsole.Write(ine2K$,e...K / name3G I I I

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 t,pe. -9 is a case sensiti e language so oid and #oid are different.

Aou D.N@+ need to sa e ,our program with same file name as of ,our class containing Main23 method.

+here can be multiple Main23 methods in ,our program.

A namespace is onl, logical collection of classes with no ph,sical mapping on disk 2unlike :a a3. )nclosing ,our class in some namespace is optional. Aou 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.

Multiple Main Method

+he designers of -9 included a mechanism b, which ,ou can define more than one class with a Main method. Aou can then use the &main8YclassNameZ switch with the -9 compiler to specif, which classs Main method to use. using S,stemG class MainS H static oid Main23 H -onsole.Write(ine2KMainSK3G I I class Main= H static oid Main23 H -onsole.Write(ine2KMain=K3G I I

+o compile this application so that the MainS.Main method is used as the applications entr, point csc MultipleMain.cs &main8MainS +o compile this application so that the Main=.Main method is used as the applications entr, 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 double Note that some of the abo e con ersion will cause loss of precision but not loss of magnitude.

)mplicit Con0ersion E'ample


using S,stemG namespace McaJ-Sharp H class -on ert H public static oid Main23 H

char cV@A@G int iVcG -onsole.Write(ine2i3G long lV=BCJ%PN[S>>G float fVlG -onsole.Write(ine2f3G &&(oss of 6recision

I I I

OutPut : 65 2.345679E+ ! Con0erts (trin# to )nte#er


using S,stemG namespace McaJ-Sharp H class S<uare H static oid Main2StringTU args3 H int num,powG -onsole.Write2K)nter the number 8 K3G num V IntB=.6arse2-onsole.*ead(ine233G powVnum R numG -onsole.Write(ine2KS<uare is 8 K /pow3G I I I

OutPut : Enter the number : # $%uare is : &# Declarin# Constants


using S,stemG namespace McaJ-Sharp H class Area H static oid Main2StringTU args3 H const float 6iVB.SC!G float radius,areaG -onsole.Write2K)nter the *adius 8 K3G radius V float.6arse2-onsole.*ead(ine233G &&-on erts string to float areaV6iRradiusRradiusG -onsole.Write(ine2KArea of -ircle is 8 K /area3G I I I

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 beha ior. (tate is represented b, a set of ariables F the alues the, contain. 6eha0ior is 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 s,stem.

.b5ect take up space in memor, and ha e an associated address like a record in 6ascal or structure in -. .b5ects are runtime instance of some class. !or )"ample8 6erson pS,p=G pS V new person23G p= V new person23G

Class

A class is a template from which ob5ects are created. +hat is ob5ects are instance of a

class. When ,ou create a class, ,ou are creating a new data7t,pe. Aou can use this t,pe to declare ob5ects of that t,pe. -lass defines structure and beha ior 2data F code3 that will be shared b, a set of ob5ects class -lassName H t,pe ariableSG t,pe ariable=G t,pe methodnameS 2parameter list3 H bod, of methodG I t,pe methodname= 2parameter list3 H bod, of methodG I I

Access Modifiers Access Modifier Description

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. T$e mem%er is not *isi%le outsi'e t$e &lass an' &an %e a&&esse' %) 'eri*e' &lasses onl). 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.

protected private

internal

T$e mem%er is *isi%le onl) ,it$in t$e &urrent &ompilation unit. T$e internal a&&ess mo'i#ier &reates a $)%ri' o# public an' protected a&&essi%ilit) 'epen'ing on ,$ere t$e &o'e resi'es.

using S,stemG namespace McaJ-Sharp H class $o" H internal double widthG internal double heightG internal double depthG I class $o"Demo H static oid Main 23 H $o" m,bo" V new $o" 23G double olG m,bo".width VS>G m,bo".height V =>G m,bo".depth V B>G ol V m,bo".width R m,bo".height R m,bo".depthG -onsole.Write(ine2K#olume is8 7 K / ol3G I I I


depth.

)ach ob5ect contains its own cop, of each ariable defined b, the class. So, e er, $o" ob5ect contains its own cop, of the instance ariables width, height and

+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" m,bo"G

&& declare ref. to ob5ect which contains null alue.

'

m,bo" V new $o" 23G

&& allocate a $o" ob5ect.

-eneral form of a new


class ar V new classname 23G m,bo" V new $o" 23G Where8 class ar V ariable of the class t,pe. 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" bS V new $o" 23G $o" b= V new bSG After this e"ecutes, bS and b= will both refer to the same ob5ect. +he assignment of bS 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 bS. +hus, an, changes made to the ob5ect through b= will affect the ob5ect to which bS is referring, since the, are the same ob5ect.

)ntroducin# Methods
t,pe name 2parameter7list3 H bod, of method I Where8 T,pe : Specifies the t,pe of data returned b, the method. If the method does not return a alue its return t,pe must be oid. Name: Specifies the name of the method. 2arameter+list: It is a se<uence of t,pe F identifiers pairs b, commas. separated

6arameters are ariables that recei e the alue of the argument passed to the method when it is called. If the method has no parameters, then the parameter list will be empt,. Methods that ha e a return t,pe other than oid return a alue to the calling routine

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 S,stemG namespace McaJ-Sharp H class $o" H internal double width, height, depthG internal oid olume23 H -onsole.Write(ine2L#olume is8 7L/widthRheightRdepth3G I I class $o"Demo#oid H static oid Main 23 H $o" M,$o"S V new $o" 23G $o" M,$o"= V new $o" 23G M,$o"S.width VS>G M,$o"S.height V=>G M,$o"S.depth VSJG M,$o"=.width VS>G M,$o"=.height VSJG M,$o"=.depth V=JG M,$o"S. olume 23G M,$o"=. olume 23G I I !eturnin# a 0alue using S,stemG namespace McaJ-Sharp H class $o" H internal double width, height, depthG internal double olume23 H return widthRheightRdepthG I I I

class $o"Demo+,pe H static oid Main 23 H $o" M,$o"S V new $o" 23G $o" M,$o"= V new $o" 23G double olG M,$o"S.width VS>G M,$o"S.height VSJG M,$o"S.depth V=>G M,$o"=.width V=G M,$o"=.height VBG M,$o"=.depth VJG ol V M,$o"S. olume 23G -onsole.Write(ine 2L#olume is8 7L/ ol3G ol V M,$o"=. olume 23G -onsole.Write(ine 2L#olume is8 7L/ ol3G I I I Method which takes parameter int s<uare 23 H return S> R S>G I It will return the s<uare of S> but this method is specified to onl, S>. If ,ou modif, the method so that it takes a parameter. int s<uare 2int i3 H return i R iG I int "G " V s<uare 2J3G

A parameter is a ariable defined b, a method that recei es a alue when the method is called. !or e"ample in s<uare 23, i is a parameter. An argument is alue that is passed to a method when it is in oked. !or e"ample in s<uare 2S>>3, passes S>> as an argument.

using S,stemG namespace McaJ-Sharp H class $o" H internal double width, height, depthG internal double olume23 H return widthRheightRdepthG I internal oid SetDim 2double w, double h, double d3 H width V wG

height V hG depth V dG I I

class $o"Demo6ara H static oid Main 23 H double olG $o" M,$o"S V new $o" 23G $o" M,$o"= V new $o" 23G M,$o"S.SetDim 2S>,SJ,=J3G M,$o"=.SetDim 2B,J,P3G ol V M,$o"S. olume 23G -onsole.Write(ine2L#olume is8 7L/ ol3G ol V M,$o"=. olume 23G -onsole.Write(ine2L#olume is8 7L/ ol3G I I I

Constructor

It can be tedious to initiali4e the entire ariable in a class each time an instance is created. ) en when ,ou add functions like SetDim 23, it would be simpler and more concise to ha e all of the setup done at the time the ob5ect is first created. $ecause the re<uirement for initiali4ation is so common, -9 allows ob5ects to initiali4e themsel es when the, are created. +his automatic initiali4ation is performed through the use of constructor.

A constructor initiali4es an ob5ect immediatel, upon creation.

It has the same name as the class in which it resides and is s,ntacticall, similar to a method. .nce defined, the constructor is automaticall, called immediatel, after the ob5ect is created, before the new operator completes. -onstructor do not ha e return t,pe not e en oid.

using S,stemG namespace McaJ-Sharp H class $o" H internal double width, height, depthG internal $o" 23 H width V S>G height V S>G depth V S>G I

internal double olume23 H return widthRheightRdepthG I I class $o"Demo-on H static oid Main 23 H double olG $o" M,$o"S V new $o" 23G $o" M,$o"= V new $o" 23G ol V M,$o"S. olume 23G -onsole.Write(ine2L#olume is8 7L/ ol3G ol V M,$o"=. olume 23G -onsole.Write(ine 2L#olume is8 7L/ ol3G I I I

M,$o"S and M,$o"= were initiali4ed b, the $o" 23 constructor when the, were created. $oth will print the same alue S>>>. 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 S,stemG namespace McaJ-Sharp H class $o" H internal double width, height, depthG internal $o" 2double w, double h, double d3 H width V wG height V hG depth V dG I internal double olume23 H return widthRheightRdepthG I I class $o"Demo-on6ara H static oid Main 23 H double olG

$o" M,$o"S V new $o" 2S>,=>,SJ3G $o" M,$o"= V new $o" 2B,J,P3G ol V M,$o"S. olume 23G -onsole.Write(ine2L#olume is8 7L/ ol3G ol V M,$o"=. olume 23G -onsole.Write(ine 2L#olume is8 7L/ ol3G I I I

Method &0erloadin#
it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. Method o erloading is one of the wa,s that -9 supports pol,morphism. When an o erloaded method is in oked, -9 uses the t,pe and&or number of arguments as its guide to determine which ersion of the o erloaded method to actuall, call. +hus, o erloaded methods must differ in the t,pe and&or number of their parameters. . erloaded methods ma, ha e different return t,pesG the return t,pe alone is insufficient to distinguish two ersions of a method. When -9 encounters a call to an o erloaded method, it simpl, e"ecutes the ersion of the method whose parameters match the arguments used in the call.

using S,stemG namespace McaJ-Sharp H class . erloadDemo H internal oid test23 H -onsole.Write(ine2Lno numberM3G I internal oid test 2int a3 H if2aZ>3 -onsole.Write(ine2LH>I is 6ositi e numberM,a3G else -onsole.Write(ine2LH>I is Negati e numberM,a3G I internal oid test 2int a, int b3 H if2aZb3 -onsole.Write(ine2La 87 H>I is greater than b 87 HSIM,a , b3G else -onsole.Write(ine2Lb 87 H>I is greater than a 87 HSIM,b , a3G I I -lass . erload H static oid Main23 H . erloadDemo odV new . erloadDemo23G .d.test23G

.d.test2S>3G .d.test2S>,=>3G I I I

Constructor &0erloadin#

In addition to o erloading normal methods, we can also o erload constructor methods.

class $o" H internal double width, height, depthG internal $o" 2double w, double h, double d3 H width V wG height V hG depth V dG I internal $o"23 H width V JG height V JG depth V JG I internal $o" 2double len3 H width V height V depth V lenG I internal double olume23 H return widthRheightRdepthG I I class . erload-ons H static oid Main 23 H $o" M,$o"S V new $o"2S>,=>,SJ3G $o" M,$o"= V new $o"23G $o" M,-ube V new $o"2P3G double olG ol V M,$o"S. olume23G -onsole.Write(ine2K#olume of M,$o"S is8 K/ ol3G ol V M,$o"=. olume23G -onsole.Write(ine2K#olume of M,$o"= is8 K/ ol3G ol V M,-ube. olume23G -onsole.Write(ine2K#olume of M,-ube is8 7K/ ol3G I I

OutPut : +olume of ,!-o.' is 3000 +olume of ,!-o.& is '&# +olume of ,!(ube is 3*3

&b5ect as 2arameter
class +est 23 H internal int a, bG internal +est 2int i, int 53 H a V iG b V 5G I internal bool e<uals 2+est ob53 H if 2ob5.a VV a FF ob5.b VV b3 H return trueG I else H return falseG I I I class 6ass.b H static oid Main 2String argsTU3 H +est obS V new +est 2S>>,==3G +est ob= V new +est 2S>>,==3G +est obB V new +est 27S,7S3G -onsole.Write(ine2LobS VV ob=M/obS.e<uals2ob=33G -onsole.Write(ine2LobS VV obBM/obS.e<uals2obB33G I I

OutPut : ob'//ob& True ob'/ob3 0alse

Ar#ument 2assin#

-omputer language can pass an argument to a subroutine in two wa,s8

call7b,7 alue call7b,7reference

Call+6,+4alue

When we pass a ariable of an implicit data t,pe to a method, conceptuall, the

runtime generates a cop, and passes that cop, to the method. It is actuall, a cop, of the ariable that is a ailable inside the method.

1ence if ,ou modif, a alue t,pe ariable 2passed as a parameter3 in a method, the actual alue of the ariable would not be changed outside the method. class +est H internal oid meth 2int i, int 53 H i V iR=G 5 V 5&=G I I class -all$,#alue H static oid Main23 H +est tS V new +est23G int aVSJ, bV=>G -onsole.Write(ine2Ka F b before call8 7 K/a/K K/b3G +S.meth 2a,b3G -onsole.Write(ine2Ka F b after call8 7K/a/K K/b3G I I 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 the ariable a and b .

Also, note that i and 5 are the local ariable in maths23 and a and b are local ariables in 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 call the subroutine.

ref and out ke,words

-9 pro ides a ke,word <ref=, which means that the alue t,pe will be passed b, reference instead of the default b, alue beha ior. 1ence, changes done inside the method would be reflected back after the method has been called and terminated. $oth the method signature and method calling should be declared as ref in order to o erride the b, alue characteristic to b, ref. class +est H internal oid maths 2ref int i, ref int 53 H i V iR=G

5 V 5&=G

I class -all$,*ef H static oid Main23 H +est tS V new +est23G int aVSJ, bV=>G -onsole.Write(ine2Ka F b before call8 7 K/a/K K/b3G +S.maths 2ref a, ref b3G -onsole.Write(ine2Ka F b after call8 7K/a/K K/b3G I I Output: A and b before call: 15 ! A and b after call: "! 1!

&ut ke,word

' '

In the case of the ref ke,word, the ariable must be initiali4ed before passing it to the method b, reference. -9 also pro ides the out ke,word. +his is used for passing a ariable for output purposes. using S,stemG namespace McaJ-Sharp H class +est H internal oid maths2out int i, out int 53 H i V =G 5 V CG I I class -all$,.ut H static oid Main23 H +est +S V new +est23G int a , b G +S.maths2out a, out b3G -onsole.Write(ine2Ka F b after call8 7K / a / K K / b3G I I I

OutPut : A and b after )all : & * 4alue T,pe and !eference T,pe

#alue t,pes are primiti e t,pes that are mapped directl, to the !-(. (ike IntB= maps to S,stem.IntB=, double maps to S,stem.double. All alue t,pes are stored on stack . An ob5ect of a alue t,pe stores its associated data directl, within itself.

!or )"ample 8 When we write8

double pi V B.SCSJ[G the alue B.SCSJ[ is directl, stored within pi. When we initiali4e or assign one alue t,pe with another, the data contained in the one 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 instances contained in independent ob5ects. !eference T,pe

*eference +,pes are different from alue t,pes in such a wa, that memor, is allocated to them from the heap. All the classes are of reference t,pe. -9 new operator returns the memor, address of the ob5ect. *eference t,pes are stored on the run7time heapG the, ma, onl, be accessed through a reference to that storage. !or )"ample

Arra,s M,ob5 ob5SG ob5S V new m,ob523G

+he .b5ect +,pe +he class +,pe Interfaces Delegates +he string t,pe

ob5S is reference t,pe ariable 2assuming M,ob5 is a class t,pe ariable3.compiler allocates memor, for this ob5ect on the heap and its address is stored in ob5S.

6o'in# and %nbo'in#

-9 +,pe S,stem contains three +,pes 8 #alue +,pes *eference +,pes 6ointer +,pes.


+,pes .

-9 allows us to con ert a #alue +,pe to a *eference +,pe, and back again to #alue

+he operation of -on erting a #alue +,pe to a *eference +,pe is called $o"ing and the re erse operation is called ?nbo"ing. 6o'in#

+he con ersion of alue t,pe to reference t,pe is known as bo"ing.

A bo"ing con ersion permits an, alue7t,pe to be implicitl, con erted to the t,pe ob5ect or to an, interface7t,pe implemented b, the alue7t,pe. class +est H static oid Main23 H int i V SJG ob5ect ob5 V iG && bo"ing int 5 V 2int3 ob5G && unbo"ing -onsole.Write(ine2L.b5ect is H>IM, ob53G -onsole.Write(ine2L: is H>IM,53G I I

+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 abo e operation 2.b5ect .b5 V al 3 we saw con erting a alue of a #alue +,pe into a alue of a corresponding *eference +,pe .

)nheritance

In .b5ect .riented 6rogramming the original class 2or the class that is sub7t,ped3 is called the base, parent or super class. +he class that inherits the functionalit, of the base class and e"tends it in its own wa, is called the sub, child, deri ed or inherited class.

A base class usuall, has general functionalit,, while sub7classes possess specific functionalit,. So, when sub7classing or inheriting, we go 'from generalization to specialization'. If a class $ 2sub class3 inherits a class A 2base class3, then $ would ha e a cop, of all the instance members 2fields, methods, properties3 of class A and $ can access all the members 2e"cept for the pri ate members3 of class A. 6ri ate members of a base class do get inherited in a sub7class, but the, can not be accessed b, the sub7class. Also, inheritance is said to create a,'type of relationship among classes which means sub7classes are a t,pe of base class.

When ,ou deri e a class from a base class, the deri ed class will inherit all members of the base class e"cept constructors

)nheritance in C/

-9, like :a a and contrar, to -//, allows onl, single class inheritance. Multiple inheritance of classes is not allowed in -9.\

+he .b5ect class defined in the S,stem namespace is implicitl, the ultimate base class of all the classes in -9 and the .N)+ framework Interfaces in -9 can inherit more than one interface So, multiple inheritance of interfaces is allowed in -9 similar to :a a. +o inherit one class from another, use the following s,nta"8 class Yderi ed-lassZ 8 Ybase-lassZ

4irtual Method

In ob5ect7oriented programming, a irtual function or irtual method is a function or method whose beha ior can be o erridden within an inheriting class b, a function with the same signature. When an instance method declaration includes a irtual modifier, that method is said to be a irtual method. When no irtual modifier is present, the method is said to be a non7 irtual method.

New 0>s &0erride

When used as a modifier, the new ke,word e"plicitl, hides a member inherited from a base class. When ,ou hide an inherited member, the deri ed ersion of the member replaces the base7class ersion. +he new modifier instructs the compiler to use ,our implementation instead of the base class implementation. public class $aseH public int "G public oid In oke23 HI I public class Deri ed- 8 $aseH new public oid In oke23 HI I

In this e"ample, $ase-.In oke is hidden b, Deri ed-.In oke.

We ha e an ob5ect of t,pe Animal, but it references an ob5ect of t,pe Dog. +hus ,ou can see the base class constructor getting called first followed b, the deri ed class constructor. 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 t,pe which in our case is Animal. Now when we call Sing23, we find that the deri ed class method has got called. +his is because in the base class the method is protot,ped as public irtual oid Sing23 and in the deri ed class we ha e o erridden it b, using public o erride oid Sing23.

In -9, we need to e"plicitl, use the o erride ke,word

!inall, when we call ;reet23 the base class method gets called since the deri ed class has not e en implemented the method. #$ample %it&out 'irtual( o'erride and ne% %it& %arning : using S,stemG namespace McaJ-Sharp H class A H public oid !oo23 H -onsole.Write(ine2KA88!oo23K3G I I class 6 : A ? @ class +est H static oid Main2stringTU args3 H A a V new A23G a.!oo23G >> output ++A BA::Foo"$B $ b V new $23G b.!oo23G >> output ++A BA::Foo"$B

I I I

#$ample %it& cross reference and %it&out 'irtual( o'erride and ne% %it& %arning : using S,stemG

namespace McaJ-Sharp H class A H public oid !oo23 H -onsole.Write(ine2KA88!oo23K3G I I class 6 : A H public oid !oo23 H -onsole.Write(ine2K$88!oo23K3G I I

class +est H static oid Main2stringTU args3 H A aG $ bG a V new A23G b V new $23G a.!oo23G >> output ++A BA::Foo"$B b.!oo23G >> output ++A B6::Foo"$B a V new $23G a.!oo23G >> output ++A BA::Foo"$B I I I

+here are two problems with this code.

+he output is not reall, what we, sa, from :a a, e"pected. +he method !oo23 is a non7 irtual method. -9 re<uires the use of the ke,word irtual in order for a method to actuall, be irtual. Although the code compiles and runs, the compiler produces a warning.

4irtual and &0erride Method

.nl, if a method is declared irtual, deri ed classes can o erride this method if the, are e"plicitl, declared to o erride the irtual base class method with the o0erride ke,word. #$ample %it& 'irtual ) o'erride :

using S,stemG namespace McaJ-Sharp H class A H public 0irtual oid !oo23 H -onsole.Write(ine2KA88!oo23K3G I I class 6 : A H public o0erride oid !oo23 H -onsole.Write(ine2K$88!oo23K3G I I class +est H static oid Main2stringTU args3 H A aG $ bG a V new A23G b V new $23G a.!oo23G >> output ++A BA::Foo"$B b.!oo23G >> output ++A B6::Foo"$B a V new $23G a.!oo23G >> output ++A B6::Foo"$B I I I

Method .idin# usin# New 3e,word

If a method is not o erriding the deri ed method, it is hiding it. A hiding method has to be declared using the new ke,word. When used as a modifier, the new ke,word e"plicitl, hides a member inherited from a base class. When ,ou hide an inherited member, the deri ed ersion of the member replaces the base7class ersion. #$ample %it& ne% : using S,stemG namespace McaJ-Sharp H class A H

public oid !oo23 H -onsole.Write(ine2KA88!oo23K3G I I class $ 8 A H public new oid !oo23 H -onsole.Write(ine2K$88!oo23K3G I I class +est H static oid Main2stringTU args3 H A aG $ bG a V new b V new a.!oo23G b.!oo23G A23G $23G >> output ++A BA::Foo"$B >> output ++A B6::Foo"$B

I I I

a V new $23G a.!oo23G >> output ++A BA::Foo"$B

Combinin# Method &0erridin# and .idin#

Methods of a deri ed class can both be irtual and at the same time hide the deri ed method. In order to declare such a method, both ke,words irtual and new ha e to be used in the method declaration. class A H public oid !oo23 H I I class $ 8 A H public 0irtual new oid !oo23 H -.W(2L$88!ooM3G I I -.W(2LA88!ooM3G


class $8

A class - can now declare a method !oo23 that either o errides or hides !oo23 from

class - 8 $ H public o0erride oid !oo23 H -.W(2L-88!ooM3G I && or public new oid !oo23 H -.W(2L-88!ooM3G I I

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 S,stemG class A H public A23 H -onsole.Write(ine2KAK3G I I class $ 8 A H public $23 8 base23 H -onsole.Write(ine2K$K3G I I class -on$ase H static oid Main23 H $ bVnew $23G I I *alling constructor %it& argument : using S,stemG class A

public A2int i3 H &&-onsole.Write(ine2K#alue of i in $ase -lass is H>IK,i3G I

class $ 8 A H public $2int i3 8 base2i3 H -onsole.Write(ine2K#alue of i in Deri ed -lass is H>IK,i3G I I class -on$aseArg H static oid Main23 H $ b V new $2B>3G I I

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, pro ides the signature or declaration of the abstract methods and lea es the implementation of these methods to deri ed or sub7classes. Abstract methods and abstract classes are marked with the abstract ke,word.

A class inheriting an abstract class and implementing all its abstract methods is called the concrete class of the abstract class. A class that contains at least one abstract method and therefore can ne er be instantiated. Abstract classes are created so that other classes can inherit them and implement their abstract methods.

abstract class A H abstract oid callme23G oid callmetoo23 H -onsole.Write(ine2Lthis is a concrete methodM3G I I class $ 8 A H

oid callme23 H -onsole.Write(ine2L$s implementation of callmeM3G I I class AbstractDemo H static oid main2StringTU args3 H $ bVnew $23G b.callme23G b.callmetoo23G I I

Notice that no ob5ects of class A are declared in the program. As mentioned, it is not possible to instantiate an abstract class Interface

)nterface

-9 does not support multiple inheritance means the classes in -9 cannot ha e more than one superclass. -9 pro ides an alternate approach known as interface to support the concept of multiple inheritance. An interface is declared using the interface ke,word. 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 t,pe whose members are all public and abstract b, default.

An interface is implemented b, a class. A class implementing the interface must pro ide the bod, for all themembers of the interface. +o implement an interface, a class uses the same s,nta" that is used for inheritance. A colon 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

Interface Yinterface nameZ H Member declarationsG I

)"ample S 8 Interface!irst.cs )"ample demonstrate Interfaces ma, also inherit other interfaces

using System; interface IParentInterface { void ParentMethod(); }

interface IChildInterface : IParentInterface { void ChildMethod(); } class InterfaceFirst : IChildInterface { static void Main() { InterfaceFirst i ne! InterfaceFirst(); i"ChildMethod(); i"ParentMethod(); } #u$lic void ChildMethod() { Console"%rite&ine('Child Method called"'); } #u$lic void ParentMethod() { Console"%rite&ine('Parent Method called"'); } }

)"ample = 8 Interface+est.cs

)"ample demonstrate an application implementing two interfaces. +he class implements two interfaces. using System; interface I(ddition { ))const dou$le #i int (dd(); }

*"+,;

interface IMulti#lication

{ int Mul(); } class Com#ute : I(ddition- IMulti#lication { int .-y; #u$lic Com#ute(int .- int y) { this". .; this"y y; } #u$lic int (dd() { return ./y; } #u$lic int Mul() { return .0y; } } class Interface1est { static void Main(String23 args) { Com#ute c ne! Com#ute(,4-54); Console"%rite&ine('Sum is : ' /c"(dd()); Console"%rite&ine('Multi#lication is : ' /c"Mul()); } }

)"ample B 8 Interface+estS.cs )"ample demonstrate Multiple implementation of an interface.

using System; interface (rea { dou$le Com#ute(dou$le .); } class S6uare : (rea { #u$lic dou$le Com#ute(dou$le .) { return .0.; } } class Circle : (rea { #u$lic dou$le Com#ute(dou$le .)

{ return *"+,0.0.; } } class Interface1est+ { static void Main() { S6uare s ne! S6uare(); Circle c ne! 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 of name conflict. +his problem is still there in more than one interface. !or e". Interface iS H oid disp23GI Interface i= H oid disp23GI -lass c 8 iS,i= H public oid disp23HI I In abo e situation cS.disp23 implement iS.disp23 or i=.disp23X It reports an error.

-9 supports a techni<ue known as )"plicit Interface Implementation, which allows a method to specif, e"plicitl, the name of the interface it is implementing )"ample C 8 Interface+est=.cs

using System; interface I+ { void 9is#(); } interface I8 { void 9is#(); } class C+ : I+-I8

{ #u$lic void I+"9is#() { Console"%rite&ine('I+ 9is#lay Method'); } #u$lic void I8"9is#() { Console"%rite&ine('I8 9is#lay Method'); } } class Interface1est8 { static void Main() { C+ c ne! C+(); I+ i (I+) c; reference their mem$er i"9is#(); ))casting : o$:ect is cast to interface ty#es to

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 deri ed class but can@t be a base class.

A sealed class cannot also be an abstract class. $ecause abstract class has to pro ide functionalit, and here we are restricting it to inherit.

;eneral !orm is sealed class A H ]. ]. I sealed class $ 8 Some-lass H ..... ].. I )"ample S 8 Demonstration of sealed class. Sealed-lassDemo.cs

using System; names#ace Mca7CShar#

{ #u$lic sealed class ;aseClass { #u$lic void 9is#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) class SealedClass9emo { static void Main(string23 args) { ;aseClass o$: o$:"9is#lay(); ne! ;aseClass();

} } }

(ealed Method

When method declaration includes the sealed modifier, the method is said to be a sealed method. Deri ed class cannot o erride this method. )"ample = 8 Demonstration of Sealed Method. SealedMethodDemo.cs

using System; names#ace Mca7CShar# {

#u$lic class ;aseClass { #u$lic virtual void 9is#lay() { Console"%rite&ine(';ase <irtual method'); } } #u$lic class 9erivedClass : ;aseClass { )) =o! the dis#lay method have $een sealed and can;t $e overridden #u$lic override sealed void 9is#lay() { Console"%rite&ine('Sealed Method'); } }

)0#u$lic class 1hirdClass : 9erivedClass {

#u$lic override void 9is#lay() { Console"%rite&ine('>ere !e try again to override dis#lay method !hich is not #ossi$le and !ill give error'); } }0) class SealedMethod9emo { static void Main(string23 args) {

9erivedClass o$+ o$+"9is#lay();

ne! 9erivedClass();

)01hirdClass o$8 ne! 1hirdClass(); o$8"9is#lay();0) )0;aseClass o$8; o$8 ne! 1hirdClass(); o$8"9is#lay();0)

} } }

Вам также может понравиться