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

C# Language Basics This article provides an overview of the C# Language.

The various elements and building blocks of the C# language are explained. What is C# all about? C# was developed at Microsoft. It is an object oriented programming language and provides excellent features such as strong t!pe checking" arra! bounds checking and automatic garbage collection. #e will explore these and several other features in this article. C# has features that make it an excellent choice for developing robust distributed n tier $nterprise applications" web applications" windows applications and embedded s!stems. It is used for building applications ranging from the ver! large that use sophisticated operating s!stems" down to the ver! small having specialist functions Getting Started: %ere is a ver! simple &%ello #orld' program written using C#. The code for C# program is written in text files with an extension &.cs' $xample( )* Create a text file &+irst.cs' ,* T!pe the following code and -save.

using System; class myClass { static void Main() { Console.WriteLine("Hello World"); } }

/* +rom the command line compile the above code b! t!ping the following csc First.cs 0* This creates First.e e 1* 2un this exe from the command line and !ou see an output 3 Hello World %aving seen the example above we will now review the concepts and elements of the C# programming language. 4fter that we will review the above example once again to understand what each line of code does. To get a better grasp of the C# language it is helpful if !ou have some programming experience and even better if !ou have experience in 5bject 5riented 6rogramming. #e now examine the C# language concepts and elements one b! one.

A) OOP C# is an object oriented 6rogramming language and it supports the 5bject 5riented 6rogramming Methodolog!. #hen creating a software solution !ou can represent the real world entities as &objects' of different &t!pes'. a. T !es: C# supports mainl! two kinds of t!pes( value t!pes and 2eference t!pes. The difference lies in the wa! in which handles these tow kinds of t!pes. $xamples of value t!pes are 3 char" int" structures" enums . $xamples of 2eference t!pes are 3 class" interface" delegate" arra!s i. "ariables represent storage locations. $ver! variable is of a specific -t!pe.. This determines what values can be stored in it. ii. #ield is a variable that is associated with a Class or 7truct" or an instance of a class or struct. iii. Para$eters: There are four kinds of parameters( value parameters" reference parameters" output parameters" and parameter arra!s. i%. Classes: Classes are blueprints for objects. 8ou instantiate an object from class. 4n object thus instantiated if said to be of a reference t!pes. 4s C# is an 5bject 5riented 6rogramming Language a class can inherit from another class" and can implement interfaces. $ach Class can have one or members such as methods" properties" constants" fields" events" constructors" destructors and so on. %. Structs: 7tructs are similar to classes in man! wa!s. The! have members and the! can implement interfaces. The! are fundamentall! different from classes. 7T29CT7 are value t!pes. 7T29CT values are stored :on the stack: or :in line:. The! cannot be inherited from an! other class or reference t!pe. %i. &nter'aces: #hat is an interface; 4n Interface simplifies a complex process b! providing eas! to use methods. Consider !ou need to change the channel on !our T< or increase its volume" how do we do this" we use a Remote Control to change the channel or increase the volume. In this context" a Remote Control acts as an interface between !ou and !our T<. 9sing a Remote Control one can perform re=uired operation and control various functionalit! available in T<. 4n interface defines a contract. #hen a class or a struct implements an interface with the help of methods and properties. 4 t!pe >CL477 or 7T29CT* that implements an interface must adhere to its contract. Interfaces can contain methods" properties" events" and indexers as members. %ii. (elegates: C# implements the functionalit! of function pointers using ?elegates. 4 delegate instance encapsulates a list of one or more methods" each of which is referred to as a callable entit!. #hen a delegate instance is invoked it causes the delegate instance@s callable entit! to be invoked.

%iii. )nu$s: 4n enum t!pe declaration defines a t!pe name for a related group of s!mbolic constants. i*. Prede'ined t !es: The predefined value t!pes include signed integral t!pes >sb!te" short" int" and long* unsigned integral t!pes >b!te" ushort" uint" and ulong* floating point t!pes >float and double* bool char decimal

*. +ullable t !es These are constructed using the -;. t!pe modifier. int; is the nullable form of the predefined t!pe int. int! " #$; int! % " null; The nullable t!pe is a structure. This structure has two members ( 4 value of the underl!ing t!pe >&<alue'* 4 Aoolean null indicator >&%as<alue'* Has&alue is true for a non null instance and false for a null instance. #hen Has&alue is true" the <alue propert! returns the contained value. #hen Has&alue is false" an attempt to access the <alue propert! throws an exception. i' ( .Has&alue) Console.WriteLine( .&alue); 4n implicit conversion exists from an! non nullable value t!pe to a nullable form of that t!pe. B) +a$es!aces C# programs are organiBed using namespaces. Camespaces provide a hierarchical means of organiBing the elements of one or more programs. The! also provide a wa! of presenting program elements that are exposed to other programs. +or instance in our example using System; class myClass { static void Main() { Console.WriteLine("Hello World"); } }

The statement 3 &using s!stemD' helps us use the &Console' class in it. 4 namespace declaration consists of the ke!word namespace" followed b! a namespace name and bod! names(ace Com(any).*e(t$ { class manager {} class em( {} } names(ace Com(any) { names(ace *e(t$ { class manager {} class em( {} } }

Camespaces are open ended" and two namespace declarations with the same full! =ualified name contribute to the same declaration space In the example names(ace Com(any).*e(t$ { class manager {} } names(ace Com(any).*e(t$ { class em( {} }

the two namespace declarations above contribute to the same declaration space" Asse$blies 4ssemblies are used for ph!sical packaging and deplo!ment. 4n assembl! can contain the executable code and references to other assemblies. C) Language Gra$$ar a. )*!ressions: 4n expression is a se=uence of operands >variables" literals" etc* and operators 4n expression can be classified as one of the following( value variable namespace

t!pe method group propert! access event access indexer access void or Cothing

The output of an expression can never be a namespace" t!pe" method group" or b. State$ents: C# statements can be classified as one of the following( labeled statement declaration statement embedded statement embedded statement( >statements that appear within other statements* empt! statement expression statement selection statement iteration statement jump statement tr! statement checked statement unchecked statement lock statement using statement

c. Constants: 4 constant is a class member that represents a constant value( a value that can be computed at compile time. Constants can depend on other constants within the same program. class myClass { (u+lic const int , " ); (u+lic const int - " , . ); } d. #ields: 4 field is a member that represents a variable associated with an object or class. e. O!erators: The operators of an expression indicate which operations to appl! to the operands. $xamples of operators( E" " F" G" new. There are three kinds of

operators( Unary operators. The unar! operators take one operand and use either prefix notation >such as 3 counter* or postfix notation >such as counterEE*. Binary operators. The binar! operators take two operands and all use infix notation >such as int4 E int8*. Ternary operator. 5nl! one ternar! operator" ;(" existsD it takes three operands and uses infix notation >condition; intH( int8*.

Certain operators can be overloaded. 5perator overloading permits user defined behavior for the operator. ') ,ethods: 4 method is a member of the class. It implements functionalit! or behavior or action that can be performed b! an instance of that class. Methods can have one or more formal parameters" an optional return value g) Pro!erties: 4 propert! is a member of the class. It provides access to a feature or characteristic of an instance of the class. In the example below( class car has a propert! CarColor (u+lic class car { (rivate string /CarColor; (u+lic string CarColor { get { return /CarColor; } set { /CarColor " value; } } }

h) )%ent: 4n event is also a member of the class. It enables an object or class to provide notifications when an event occurs. $xample (u+lic delegate void 0ventHandler(o+1ect sender2 System.0vent,rgs e);

(u+lic class -utton { (u+lic event 0ventHandler Clic3; (u+lic void 4eset() { Clic3 " null; } } using System; (u+lic class Form) { (u+lic Form)() { -utton).Clic3 ." ne5 0ventHandler(doSomet6ing); } -utton -utton) " ne5 -utton(); void doSomet6ing(o+1ect sender2 0vent,rgs e) { Console.WriteLine("-utton) 5as clic3ed and 7 did Somet6ing8"); } (u+lic void *isconnect() { -utton).Clic3 9" ne5 0ventHandler(doSomet6ing); } }

i) Co$$ents: Two forms of comments are supported( delimited comments and single line comments. 4 delimited comment begins with the characters GF and ends with the characters FG. ?elimited comments can occup! a portion of a line" a single line" or multiple lines. 4 single line comment begins with the characters GG and extends to the end of the line. :; <6is is my First =rogram <6is is 56ere it gets started ;: class myFirst=rogram { static void Main() { System.Console.WriteLine("Welcome ,+oard8"); :: Comment } }

-) Conditional State$ents The if statement selects a statement for execution based on the value of a Aoolean expression. $xamples( i' ( +oolean9e (ression ) em+edded9statement i' ( +oolean9e (ression ) em+edded9statement else em+edded9statement i' ( ) i' (y) F(); else >(); i' ( ) { i' (y) { F(); } else { >(); } } The switch statement : Based on the value of the switch expression. The switch statement matches a switch label and executes the statement(s) that corresponds to it Example: s5itc6 (iMatc6) { case ?@ Matc6ed/Aero(); +rea3; case )@ Matc6ed/Bne(); +rea3; de'ault@ Matc6ed/Cone(); +rea3; } k) Iteration statements : Iteration statements repeatedly execute an embedded statement. Types of iteration statements: while-statement do-statement for-statement foreach-statement l) Conversions conversion enables an expression of one type to be treated as another type. !onversions can be implicit or explicit. , conversion ena+les an e (ression o' one ty(e to +e treated as anot6er ty(e. Conversions can +e im(licit or e (licit. 4 conversion enables an expression of one t!pe to be treated as another t!pe.

Conversions can be implicit or explicit. $) Arra s 4n arra! is a data structure. It contains one or more variables that are accessed through computed indices. The elements of the arra!" are all of the same t!pe. n) ,e$or ,anage$ent: 5ne of the most important features of C# is automatic memor! management implemented using a -garbage collector.. The process scans thru the objects created in the program and if the object can no longer be accessed the memor! is cleared up o) &nde*ers : 4n indexer enables an object to be indexed in the same wa! as an arra!. Indexer declarations are similar to propert! declarations. The indexing parameters are provided between s=uare brackets. $xample using System; (u+lic class ,llmyCars { (rivate Car >etCar(int inde ) { ::(rocess and return a((ro(riate car } (u+lic o+1ect t6isDint inde E { get { return >etCar (inde ).&alue; } set { >etCar(inde ).&alue " value; } } } class <est { static void Main() { ,llmyCars c " ne5 ,llmyCars(); cD?E " F4olls 4oyceG;

cD)E " F,l(6a 4omeoG; cD$E " FSaa+G; } } !) Partial t !e declarations 6artial t!pe declarations allow

.. &ntroduction
I have noticed an increase in the number of articles published in the 4rchitect categor! in code project during the last few months. The number of readers for most of these articles is also high" though the ratings for the articles are not. This indicates that readers are interested in reading articles on 4rchitecture" but the =ualit! does not match their expectations. This article is a constructive attempt to groupG defineG explain all introductor! concepts of software architecture for well seasoned developers who are looking to take their next step as s!stem architects. 5ne da! I read an article that said that the richest , percent own half the world@s wealth. It also said that the richest ) percent of adults owned 0I percent of global assets in the !ear ,III. 4nd further" that the richest )I percent of adults accounted for J1 percent of the world@s total wealth. 7o there is an unbalanced distribution of wealth in the ph!sical world. %ave !ou ever thought of an unbalanced distribution of knowledge in the software world; 4ccording to m! view point" the massive expansion of the software industr! is forcing developers to use alread! implemented libraries" services and frameworks to develop software within ever shorter periods of time. The new developers are trained to use >I would sa! more often* alread! developed software components" to complete the development =uicker. The! just plug in an existing librar! and some how manage to achieve the re=uirements. Aut the sad part of the stor! is" that the! never get a training to define" design the architecture for" and implement such components. 4s the number of !ears pass b!" these developers become leads and also software architects. Their titles change" but the old legac! of not understanding" of not having an! architectural experience continues" creating a vacuum of good architects. The bottom line is that onl! a small percentage of developers know how to design a trul! object oriented s!stem. The solution to this problem is getting harder ever! da! as the aggressive nature of the software industr! does not support an eas! adjustment to existing processes" and also the related online teaching materials are either complex or less practical or sometimes even wrong. The most of them use impractical" irrelevant examples of shapes" animals and man! other ph!sical world entities to teach concepts of software architecture. There are onl! ver! few good business oriented design references. 9nfortunatel!" I m!self am no exception and am a result of this ver! same s!stem. I got the same education that all of !ou did" and also referred to the same resource set !ou all read. Coming back to the initial point" I noticed that there is a knowledge gap" increasing ever! da!" between the architects who know how to architect a s!stem properl! and the others who do not know. The ones" who know" know it right. Aut the ones" who do not know"

know nothing. Kust like the world.s wealth distribution" it is an unbalanced distribution of knowledge.

/. Bac0ground
This article began after reading and hearing the =uestions new developers have" on basics of software architecture. There are some good articles out there" but still developers struggle to understand the basic concepts" and more importantl!" the wa! to appl! them correctl!. 4s I see it" newcomers will alwa!s struggle to understand a precise definition of a new concept" because it is alwa!s a new and hence unfamiliar idea. The one" who has experience" understands the meaning" but the one who doesn.t" struggles to understand the ver! same definition. It is like that. $mplo!ers want experienced emplo!ees. 7o the! sa!" !ou need to have experience to get a job. Aut how the hell is one supposed to have that experience if no one is willing to give him a job; 4s in the general case" the start with software architecture is no exception. It will be difficult. #hen !ou start to design !our ver! first s!stem" !ou will tr! to appl! ever!thing !ou know or learned from ever!where. 8ou will feel that an interface needs to be defined for ever! class" like I did once. 8ou will find it harder to understand when and when not to do something. Kust prepare to go through a painful process. 5thers will criticiBe !ou" ma! laugh at !ou and sa! that the wa! !ou have designed it is wrong. Listen to them" and learn continuousl!. In this process !ou will also have to read and think a lot. I hope that this article will give !ou the right start for that long journe!. &The knowledge of the actions of great men, acquired by long experience in contemporary affairs, and a continual study of antiquity' 3 I read this phrase when I was reading the book named &The Art of War'" seems applicable here" isn.t it;

1. Prere2uisites
This article is an effort to provide an accurate information pool for new developers on the basics of software architecture" focusing on Object Oriented Programming >OO *. If !ou are a developer" who has a minimum of three or more !ears of continuous development experience and has that hunger to learn more" to step in to the next level to become a software architect" this article is for !ou.

3. The ,ain Content 3... What is So't4are Architecture?


7oftware 4rchitecture is defined to be the rules" heuristics and patterns governing( 6artitioning the problem and the s!stem to be built into discrete pieces Techni=ues used to create interfaces between these pieces Techni=ues used to manage overall structure and flow Techni=ues used to interface the s!stem to its environment 4ppropriate use of development and deliver! approaches" techni=ues and tools.

3./. Wh Architecture is i$!ortant?


4 class is simpl! a representation of a t!pe of ob!ect. It is the blueprintG planG template that describe the details of an ob!ect. 4 class is the blueprint from which the individual objects are created. Class is composed of three things( a name" attributes" and operations. Collapse Cop! Code
(u+lic class Student { }

4ccording to the sample given below we can sa! that the student object" named ob!ect"tudent" has created out of the "tudent class. Collapse Cop! Code
Student o+1ectStudent " ne5 Student();

In real world" !ou@ll often find man! individual objects all of the same kind. 4s an example" there ma! be thousands of other bic!cles in existence" all of the same make and model. $ach bic!cle has built from the same blueprint. In object oriented terms" we sa! that the bic!cle is an instance of the class of objects known as bic!cles. In the software world" though !ou ma! not have realiBed it" !ou have alread! used classes. +or example" the Text#ox control" !ou alwa!s used" is made out of the Text#ox class" which defines its appearance and capabilities. $ach time !ou drag a Text#ox control" !ou are actuall! creating a new instance of the Text#ox class.

3.5. 6o4 to identi' and design a Class?


This is an artD each designer uses different techni=ues to identif! classes. %owever according to 5bject 5riented ?esign 6rinciples" there are five principles that !ou must follow when design a class" 726 The 7ingle 2esponsibilit! 6rinciple 4 class should have one" and onl! one" reason to change. 5C6 The 5pen Closed 6rinciple 8ou should be able to extend a classes behavior" without modif!ing it. L76 The Liskov 7ubstitution 6rinciple ?erived classes must be substitutable for their base classes. ?I6 The ?ependenc! Inversion 6rinciple ?epend on abstractions" not on concretions. I76 The Interface 7egregation 6rinciple Make fine grained interfaces that are client specific.

+or more information on design principles" please refer to 5bject Mentor. 4dditionall! to identif! a class correctl!" !ou need to identif! the full list of leaf level functionsG operations of the s!stem >granular level use cases of the s!stem*. Then !ou can proceed to group each function to form classes >classes will group same t!pes of

functionsG operations*. %owever a well defined class must be a meaningful grouping of a set of functions and should support the re usabilit! while increasing expandabilit!G maintainabilit! of the overall s!stem. In software world the concept of dividing and con=uering is alwa!s recommended" if !ou start anal!Bing a full s!stem at the start" !ou will find it harder to manage. 7o the better approach is to identif! the module of the s!stem first and then dig deep in to each module separatel! to seek out classes. 4 software s!stem ma! consist of man! classes. Aut in an! case" when !ou have man!" it needs to be managed. Think of a big organiBation" with its work force exceeding several thousand emplo!ees >let.s take one emplo!ee as a one class*. In order to manage such a work force" !ou need to have proper management policies in place. 7ame techni=ue can be applies to manage classes of !our software s!stem as well. In order to manage the classes of a software s!stem" and to reduce the complexit!" the s!stem designers use several techni=ues" which can be grouped under four main concepts named $ncapsulation" 4bstraction" Inheritance" and olymorphism. These concepts are the four main gods of OO world and in software term" the! are called four main 5bject 5riented 6rogramming >OO * Concepts.

3.7. What is )nca!sulation 8or in'or$ation hiding)?


The encapsulation is the inclusion within a program object of all the resources need for the object to function basicall!" the methods and the data. In OO the encapsulation is mainl! achieved b! creating classes" the classes expose public methods and properties. The class is kind of a container or capsule or a cell" which encapsulate the set of methods" attribute and properties to provide its indented functionalities to other classes. In that sense" encapsulation also allows a class to change its internal implementation without hurting the overall functioning of the s!stem. That idea of encapsulation is to hide how a class does it but to allow re=uesting what to do. 7ame wa!" as another example" !ou can sa! that" there is a composite relationship in between a $ey%alue airCollection and a $ey%alue air. The two mutuall! depend on each other. .Cet and Kava uses the Composite relation to define their Collections. I have seen Composition is being used in man! other wa!s too. %owever the more important factor" that most people forget is the life time factor. The life time of the two classes that has bond with a composite relation mutuall! depend on each other. If !ou take the .net Collection to understand this" there !ou have the Collection $lement define inside >it is an inner part" hence called it is composed of* the Collection" farcing the $lement to get disposed with the Collection. If not" as an example" if !ou define the Collection and it.s $lement to be independent" then the relationship would be more of a t!pe 4ggregation" than a Composition. 7o the point is" if !ou want to bind two classes with Composite relation" more accurate wa! is to have a one define inside the other class >making it a protected or private class*. This wa! !ou are allowing the outer class to fulfill its purpose" while t!ing the lifetime of the inner class with the outer class. 7o in summar!" we can sa! that aggregation is a special kind of an association and

composition is a special kind of an aggregation. >Association&'Aggregation& 'Composition*

3.//. What is a Class (iagra$?


4 class diagrams are widel! used to describe the t!pes of objects in a s!stem and their relationships. Class diagrams model class structure and contents using design elements such as classes" packages and objects. Class diagrams describe three different perspectives when designing a s!stem" conceptual" specification" and implementation. These perspectives become evident as the diagram is created and help solidif! the design. The Class diagrams" ph!sical data models" along with the s!stem overview diagram are in m! opinion the most important diagrams that suite the current da! rapid application development re=uirements. 9ML Cotations(

3./5. What is three9tier architecture?


The three tier software architecture >also known as three la!er architectures* emerged in the )LLIs to overcome the limitations of the two tier architecture. This architecture has aggressivel! customiBed and adopted b! modern da! s!stem designer to web s!stems. Three tier is a client server architecture in which the user interface" functional process logic" data storage and data access are developed and maintained as independent modules" some time on separate platforms. The term :three&tier: or :three&layer:" as well as the concept of multi tier architectures >often refers to as three tier architecture*" seems to have originated within 2ational 7oftware. ,odel( (ata"et and t!ped (ata"et >some times business object" object collection" HML etc* are the most common use of the model. "ie4( The A" ) and A"C) files generall! handle the responsibilities of the view. Controllers( The handling of events or the controlling is usuall! done in the code behind class. In a complex n tier distributed s!stem the *%C architecture place the vital role of organiBing the presentation tier of the s!stem.

3./:. What is SOA?


4 service oriented architecture is essentiall! a collection of services. These services communicate with each other. The communication can involve either simple data passing or it could involve two or more services coordinating some activit!. 7ome means of connecting services to each other is needed. The .Cet technolog! introduces the 754 b! mean of web services.

The 754 can be used as the concept to connect multiple s!stems to provide services. It has it@s great share in the future of the IT world. 4ccording to the imaginar! diagram above" we can see how the 7ervice 5riented 4rchitecture is being used to provide a set of centraliBed services to the citiBens of a countr!. The citiBens are given a uni=ue identif!ing card" where that card carries all personal information of each citiBen. $ach service centers such as shopping complex" hospital" station" and factor! are e=uipped with a computer s!stem where that s!stem is connected to a central server" which is responsible of providing service to a cit!. 4s an example when a customer enter the shopping complex the regional computer s!stem report it to the central server and obtain information about the customer before providing access to the premises. The s!stem welcomes the customer. The customer finished the shopping and then b! the time he leaves the shopping complex" he will be asked to go through a billing process" where the regional computer s!stem will manage the process. The pa!ment will be automaticall! handled with the input details obtain from the customer identif!ing card. The regional s!stem will report to the cit! >computer s!stem of the cit!* while the cit! will report to the countr! >computer s!stem of the countr!*.

3./;. What is the (ata Access La er?


The data access la!er >?4L*" which is a ke! part of ever! n tier s!stem" is mainl! consist of a simple set of code that does basic interactions with the database or an! other storage device. These functionalities are often referred to as C29? >Create" 2etrieve" 9pdate" and ?elete*. The data access la!er need to be generic" simple" =uick and efficient as much as possible. It should not include complex applicationG business logics. I have seen s!stems with length!" complex store procedures >76*" which run through several cases before doing a simple retrieval. The! contain not onl! most part of the business logic" but application logic and user interface logic as well. If 76 is getting longer and complicated" then it is a good indication that !ou are burring !our business logic inside the data access la!er.

3.1<. What is the Business Logic La er?


I know for a fact that this is a =uestion for most" but from the other hand b! reading man! articles I have become aware that not ever!one agrees to what business logic actuall! is" and in man! cases it@s just the bridge in between the presentation la!er and the data access la!er with having nothing much" except taking from one and passing to the other. In some other cases" it is not even been well thought out" the! just take the leftovers from the presentation la!er and the data access la!er then put them in another la!er which automaticall! is called the business logic la!er. %owever there are no god said things that cannot be changed in software world. 8ou can change as and when !ou feel comfortable that the method !ou appl! is flexible enough to support the growth of !our s!stem. There are man! great wa!s" but be careful when selecting them" the! can over complicating the simple s!stem. It is a balance one needs to find with their experience. 4s a general advice when !ou define business entities" !ou must decide how to map the

data in !our tables to correctl! defined business entities. The business entities should meaningfull! define considering various t!pes of re=uirements and functioning of !our s!stem. It is recommended to identif! the business entities to encapsulate the functionalG 9I >9ser Interface* re=uirements of !our application" rather than define a separate business entit! for each table of !our database. +or example" if !ou want to combine data from couple of table to build a 9I >9ser Interface* control >#eb Control*" implement that function in the Ausiness Logic La!er with a business object that uses couple of data object to support with !our complex business re=uirement.

3.1.. What is Gang o' #our 8Go#) (esign Patterns?


The Mang of +our >Mo+* patterns are generall! considered the foundation for all other patterns. The! are categoriBed in three groups( Creational" 7tructural" and Aehavioral. %ere !ou will find information on these important patterns. Creational Patterns 4bstract +actor! Creates an instance of several families of classes Auilder 7eparates object construction from its representation +actor! Method Creates an instance of several derived classes 6rotot!pe 4 full! initialiBed instance to be copied or cloned 7ingleton 4 class of which onl! a single instance can exist 4dapter Match interfaces of different classes Aridge 7eparates an object.s interface from its implementation Composite 4 tree structure of simple and composite objects ?ecorator 4dd responsibilities to objects d!namicall! +acade 4 single class that represents an entire subs!stem +l!weight 4 fine grained instance used for efficient sharing 6rox! 4n object representing another object Chain of 2esp. 4 wa! of passing a re=uest between a chain of objects Command $ncapsulate a command re=uest as an object Interpreter 4 wa! to include language elements in a program Iterator 7e=uentiall! access the elements of a collection Mediator ?efines simplified communication between classes Memento Capture and restore an object@s internal state 5bserver 4 wa! of notif!ing change to a number of classes

Structural Patterns

Beha%ioral Patterns

7tate 4lter an object@s behavior when its state changes 7trateg! $ncapsulates an algorithm inside a class Template Method ?efer the exact steps of an algorithm to a subclass <isitor ?efines a new operation to a class without change

3.1/. What is the di''erence bet4een Abstract #actor and Builder design !atterns?
The two design patterns are fundamentall! different. %owever" when !ou learn them for the first time" !ou will see a confusing similarit!. 7o that it will make harder for !ou to understand them. Aut if !ou continue to stud! eventuall!" !ou will get afraid of design patterns too. It is like infant phobia" once !ou get afraid at !our earl! age" it sta!s with !ou forever. 7o the result would be that !ou never look back at design patterns again. Let me see whether I can solve this brain teaser for !ou. In the image below" !ou have both design pattern listed in. I am tr!ing to compare the two one on one to identif! the similarities. If !ou observe the figure carefull!" !ou will see an easil! understandable color pattern >same color is used to mark the classes that are of similar kind*. 6lease follow up with the numbers in the image when reading the listing below. Mark #.( Aoth patterns have used a generic class as the entr! class. The onl! difference is the name of the class. 5ne pattern has named it as &Client'" while the other named it as &?irector'. Mark #/( %ere again the difference is the class name. It is &4bstract+actor!' for one and &Auilder' for the other. 4dditionall! both classes are of t!pe abstract. Mark #1( 5nce again both patterns have defined two generic >#indows+actor! N ConcreteAuilder* classes. The! both have created b! inheriting their respective abstract class. Mark #3( +inall!" both seem to produce some kind of a generic output. Cow" where are we; 4ren.t the! looking almost identical; 7o then wh! are we having two different patterns here; Let.s compare the two again side b! side for one last time" but this time" focusing on the differences. Abstract +actory( $mphasiBes a famil! of product objects >either simple or complex* #uilder( +ocuses on constructing a complex object step b! step Abstract +actory( +ocus on FwhatF is made #uilder( +ocus on FhowF it is made Abstract +actory( +ocus on defining man! different t!pes of FfactoriesF to build man! FproductsF" and it is not a one builder for just one product #uilder( +ocus on building a one complex but one single FproductF

Abstract +actory( ?efers the choice of what concrete t!pe of object to make until run time #uilder( %ide the logicG operation of how to compile that complex object Abstract +actory( F$ver!F method call creates and returns different objects #uilder( 5nl! the FlastF method call returns the object" while other calls partiall! build the object

7ometimes creational patterns are complementar!( 7o !ou can join one or man! patterns when !ou design !our s!stem. 4s an example builder can use one of the other patterns to implement which components get built or in another case 4bstract +actor!" Auilder" and 6rotot!pe can use 7ingleton in their implementations. 7o the conclusion would be that the two design patterns exist to resolve two t!pe of business problems" so even though the! look similar" the! are not. I hope that this shed some light to resolve the puBBle. If !ou still don.t understand it" then this time it is not !ou" it has to be me and it is since that I don.t know how to explain it.

&nheritance in C# This article discusses Inheritance concepts in the context of C# Aefore we understand Inheritance in C# it is important to understand the ke! pla!ers involved" viB 5bjects" Classes and 7tructs Classes and 7tructs are -blue prints. or templates from which we instantiate >create* objects $xample a car ma! be created based on its blue print Car is the object and blue print is the class >or template* What are t !es? 4n object can be of the following t!pes 3 Class or 7truct There are man! differences between the two -t!pes. The main difference between the two is the wa! in which the! are stored in memor! and the wa! the! are accessed Classes are also called reference t!pes 7tructs are known as value t!pes Classes are stored in a memor! space called -heap. and 7tructs are stored in a memor! space known as -stack.

Constructors: In C#" >like other 5bjected 5riented languages* constructor is a method having the same name as the class The constructor is called when the object is being created It can have one or more parameters &nter'aces: In the context of C#" an interface provides a contract 4 class that is derived from this interface will implement the functions specified b! the interface &nheritance:

C# supports two t!pes of Inheritance mechanisms )* Implementation Inheritance ,* Interface Inheritance What is &$!le$entation &nheritance? #hen a class >t!pe* is derived from another class>t!pe* such that it inherits all the members of the base t!pe it is Implementation Inheritance What is &nter'ace &nheritance? #hen a t!pe >class or a struct* inherits onl! the signatures of the functions from another t!pe it is Interface Inheritance In general Classes can be derived from another class" hence support Implementation inheritance 4t the same time Classes can also be derived from one or more interfaces %ence the! support Interface inheritance 7tructs can derive from one more interface" hence support Interface Inheritance 7tructs cannot be derived from another class the! are alwa!s derived from 7!stem<alueT!pe ,ulti!le &nheritance: C# does not support multiple implementation inheritance 4 class cannot be derived from more than one class %owever" a class can be derived from multiple interfaces &nheritance =sage )*a$!le: %ere is a s!ntax example for using Implementation Inheritance
Class derivedClass@+aseClass { }

derivedClass is derived from baseClass &nter'ace &nheritance e*a$!le:


(rivate Class derivedClass@+aseClass 2 7nter'aceH 2 7nter'aceI { }

derivedClass is now derived from interfaces 3 InterfaceH" Interface8 7imilarl! a struct can be derived from an! number of interfaces
(rivate struct c6ildStruct@7nter'aceH2 7nter'aceI { }

"irtual ,ethods: If a function or a propert! in the base class is declared as virtual it can be overridden in an! derived classes ,sage -xample.
class +aseClass { (u+lic virtual int 'nCount() { return )?; }

} class derivedClass @+aseClass { (u+lic override int 'nCount() { return )??; } }

This is useful because the compiler verifies that the -override. function has the same signature as the virtual function 6iding ,ethods: 7imilar to the above scenario if the methods are declared in a child and base class with the same signature but without the ke! words virtual and override" the child class function is said to hide the base class function
class some-aseClass { } class a+cClass@some-aseClass { (u+lic int 'n,ge() { return JJ; } } class grandc6ildClass@ a+cClass { (u+lic int 'n,ge() { return )?; } }

&nheritance in C# 9 Page /
Calling #unctions 'ro$ the Base Class: To call a function from the base class simpl! use the ke! word basefunctionname/0
class +asicMem+er { (u+lic virtual 'loat mem+ers6i(Fee() { return )??; } } class vi(Mem+er@+asicMem+er { (u+lic override 'loat mem+ers6i(Fee() {

return $??; } (u+lic 'loat (romoMem+ers6i(Fee() { return +asemem+ers6i(Fee() . K?; } }

>C# su!!orts $ulti!le inheritance using inter'aces.?9 Interfaces are IM6L$M$CT$?. Cot inherited into a Class. The Interface signatures are defined b! the class that applies the interface. 7o" the statement that &Interfaces are inherited' is )IIO wrong. Aut there is a concept of an interface being inherited into a class. Take a look at the following code(
inter'ace 7Bne { void *emo(); } inter'ace 7<5o @ 7Bne { void Somet6ing(); } class HIA @ 7<5o { (u+lic void *emo() { ... } (u+lic void Somet6ing { ...} }

Cow" in this example" !ou can see that the class &H8P' is implementing the &ITwo' interface. Aut this interface itself is inherited from &I5ne'. %ence" the class has to provide both the method signatures. What are Abstract Classes? )* 4n abstract class cannot be instantiated ,* 4n abstract class can have one or more abstract functions /* 4bstract functions are virtual 0* The! do not have an! implementation 1* The! need to be overridden and implemented in a derived non abstract class 4bstract Classes and +unctions example(
a+stract class Car { (u+lic int 6eadlig6ts " $; (u+lic a+stract (rice(); }

Sealed Classes: If a class is declared as 7ealed !ou cannot inherit from that class ?eclaring a method as sealed prevents it from being overridden
sealed class LastManStanding

{ }

The compiler gives an error if an! other class tries to derive from the above class
class +an3Manager { (u+lic sealed override +ool aut6ori%e() { } }

The compiler gives an error if !ou override the above method Constructors and &nheritance: C# allocates a default Bero parameter constructor to ever! class that does not have an! explicit constructors defined If !ou instantiate a child class" all the constructors in the hierarch! are called The base call constructor is called first and then the next child class constructor This se=uence continues until all the constructors are called If an explicit constructor is defined for a class an!where in the hierarch! there is a possibilit! that the above chain is broken If this is the case the compiler raises an $rror and the code will not compile +or instance" if !ou declare an explicit constructor with one or more parameters the above described se=uence of calls to constructors in the class hierarch! which was being handled automaticall! is now broken This is because when !ou suppl! a constructor C# does not provide a default constructor In this case" we have to explicitl! maintain the -chain. 4nother scenario for this error is when !ou define an explicit constructor with Bero parameters and mark it as private The compiler will raise an error in this case "isibilit ,odi'iers in C#: !ublic: 4n! t!pes or members can be prefixed with this modifer If a member or t!pe is prefixed with public it is visible to all the code !rotected: It can be used for an! member or a nested t!pe This causes the memberGnested t!pe to be visible to an! derived t!pe !ri%ate: This can be used for an! t!pe or member and the memberGt!pe will be visible onl! inside the t!pe where it was defined internal: This causes the memberGnested t!pe to be visible within the assembl! where it is defined !rotected or internal: This causes the memberGnested t!pe to be visible within the assembl! where it is defined and an! derived t!pe &nter'aces: #hen a class derives from an Interface it implements the functions specified b! the interface (e'ining an &nter'ace #e can define an interface as follows(
(u+lic inter'ace 7+an3Manager

{ +ool aut6ori%e(); }

&$!le$enting an &nter'ace The above interface can be implemented as follows(


(u+lic class ne5Manager@7+an3Manager { (u+lic +ool aut6ori%e() { ::(rocess return true; } }

(eri%ing an &nter'ace Interfaces can be derived from other interfaces -xample.


(u+lic inter'ace 7+ranc6Manager@7+an3Manager { (u+lic string send4e(orts(); }

Su$$ar : In this article we discussed Inheritance as implemented in C# and C$T #e also reviewed the ke! pla!ers involved 3 Classes" 7tructs and Interfaces

&ntroduction
Aroadl! speaking" a constructor is a method in the class which gets executed when its object is created. 9suall!" we put the initialiBation code in the constructor. #riting a constructor in the class is damn simple" have a look at the following sample( Collapse Cop! Code
(u+lic class mySam(leClass { (u+lic mySam(leClass() { :: <6is is t6e constructor met6od. } :: rest o' t6e class mem+ers goes 6ere. }

#hen the object of this class is instantiated" this constructor will be executed. 7omething like this( Collapse Cop! Code
mySam(leClass o+1 " ne5 mySam(leClass() :: ,t t6is time t6e code in t6e constructor 5ill :: +e e ecuted

Constructor O%erloading
C# supports overloading of constructors" that means" we can have constructors with different sets of parameters. 7o" our class can be like this( Collapse Cop! Code
(u+lic class mySam(leClass { (u+lic mySam(leClass() { :: <6is is t6e no (arameter constructor met6od. :: First Constructor } (u+lic mySam(leClass(int ,ge) { :: <6is is t6e constructor 5it6 one (arameter. :: Second Constructor } (u+lic mySam(leClass(int ,ge2 string Came) { :: <6is is t6e constructor 5it6 t5o (arameters. :: <6ird Constructor } :: rest o' t6e class mem+ers goes 6ere.

#ell" note here that call to the constructor now depends on the wa! !ou instantiate the object. +or example( Collapse Cop! Code
mySam(leClass o+1 " ne5 mySam(leClass() :: ,t t6is time t6e code o' no (arameter :: constructor (First Constructor)5ill +e e ecuted mySam(leClass o+1 " ne5 mySam(leClass()$) :: ,t t6is time t6e code o' one (arameter :: constructor(Second Constructor)5ill +e :: e ecuted.

The call to the constructors is completel! governed b! the rules of overloading here.

Calling Constructor 'ro$ another Constructor


8ou can alwa!s make a call to one constructor from within another. 7a!" for example( Collapse Cop! Code
(u+lic class mySam(leClass { (u+lic mySam(leClass()@ t6is()?) { :: <6is is t6e no (arameter constructor met6od.

:: First Constructor

(u+lic mySam(leClass(int ,ge) { :: <6is is t6e constructor 5it6 one (arameter. :: Second Constructor }

<er! first of all" let us see what is this s!ntax( Collapse Cop! Code
(u+lic mySam(leClass()@ t6is()?)

%ere" this refers to same class" so when we sa! this>)I*" we actuall! mean execute the public m!7ampleClass>int 4ge* method. The above wa! of calling the method is called initialiBer. #e can have at the most one initialiBer in this wa! in the method. 4nother thing which we must know is the execution se=uence i.e." which method will be executed when. %ere" if I instantiate the object as( Collapse Cop! Code
mySam(leClass o+1 " ne5 mySam(leClass()

Then the code of public m!7ampleClass>int 4ge* will be executed before the code of mySam(leClass(). 7o" practicall! the definition of the method( Collapse Cop! Code
(u+lic mySam(leClass()@ t6is()?) { :: <6is is t6e no (arameter constructor met6od. :: First Constructor }

is e=uivalent to( Collapse Cop! Code


(u+lic mySam(leClass() { mySam(leClass()?) :: <6is is t6e no (arameter constructor met6od. :: First Constructor }

+ote( 4bove >just above this line* code is mentioned there for pure analog! and will not compile. The intention here is to tell the flow of execution if initialiBers are used. #e cannot make an explicit call to the constructors in C#" treating them as if an! simple method" for example( statement mySam(leClass()?) in the above code will not work. The onl! wa! !ou can call one constructor from another is through initialiBers. +or the <A.C$T programmers( !ou can make the call to another constructor of the same class b! the s!ntax Me.Cew>param list*" but it should be the first line of !our calling constructor method. 7o ultimatel!" the code of the called constructor runs prior to the code of the calling constructor" which is same as initialiBers here.

Cote that onl! this and base >we will see it further* ke!words are allowed in initialiBers" other method calls will raise an error. This is sometimes called Constructor chaining. %uff 7imple thing made tough" but this is how it is. 4n!wa!" let us proceed further.

Beha%ior o' Constructors in &nheritance


Let us first create the inherited class. Collapse Cop! Code
(u+lic class my-aseClass { (u+lic my-aseClass() { :: Code 'or First -ase class Constructor } (u+lic my-aseClass(int ,ge) { :: Code 'or Second -ase class Constructor } :: Bt6er class mem+ers goes 6ere

(u+lic class my*erivedClass @ my-aseClass :: Cote t6at 7 am in6eriting t6e class 6ere. { (u+lic my*erivedClass() { :: Code 'or t6e First my*erivedClass Constructor. } (u+lic my*erivedClass(int ,ge)@+ase(,ge) { :: Code 'or t6e Second my*erivedClass Constructor. } :: Bt6er class mem+ers goes 6ere }

Cow" what will be the execution se=uence here( If I create the object of the derived class as( Collapse Cop! Code
my*erivedClass o+1 " ne5 my*erivedClass()

Then the se=uence of execution will be( public m!AaseClass>* method. and then public m!?erivedClass>* method. Cote( If we do not provide initialiBer referring to the base class constructor then it

executes the no parameter constructor of the base class. Cote one thing here( we are not making an! explicit call to the constructor of base class neither b! initialiBer nor b! the base ke!word" but it is still executing. This is the normal behavior of the constructor. If I create an object of the derived class as( Collapse Cop! Code
my*erivedClass o+1 " ne5 my*erivedClass()L)

Then the se=uence of execution will be( public m!AaseClass>int 4ge* method and then public m!?erivedClass>int 4ge* method %ere" the new ke!word base has come into picture. This refers to the base class of the current class. 7o" here it refers to the my-aseClass. 4nd base>)I* refers to the call to m!AaseClass>int 4ge* method. 4lso note the usage of ,ge variable in the s!ntax( public m!?erivedClass>int 4ge*(base>4ge*. Q9nderstanding it is left to the readerR.

Pri%ate Constructors
6rivate constructors" the constructors with the :private: access modifier" are a bit special case. It is because we can neither create the object of the class" nor can we inherit the class with onl! private constructors. Aut !es" we can have the set of public constructors along with the private constructors in the class and the public constructors can access the private constructors from within the class through constructor chaining. 7a! for example" m! class is something like this ( Collapse Cop! Code
(u+lic class myClass { (rivate MyClass() { Console.WriteLine("<6is is no (arameter Constructor"); } (u+lic MyClass(int var)@t6is() { Console.WriteLine("<6is is one (arameter Constructor"); } :: Bt6er class met6ods goes 6ere }

Then we can create the object of this class b! the statement( Collapse Cop! Code
MyClass o+1 " ne5 MyClass()?);

The above statement will work fine" but the statement Collapse Cop! Code

MyClass o+1 " ne5 MyClass();

will raise an error ( 1Constructors2*yClass2*yClass/01 is inaccessible due to its protection le3el It is possible to have the class with onl! the private constructors. Aut !es as I said" such class can neither be instantiated nor be inherited. If we tr! to inherit the class with onl! private constructors then we will get the same error as above. 4lso recall" once !ou provide constructor from !our side the compiler will not add the no parameter public constructor to !our class. #ell" one of the usage scenarios of such class could be when !ou have onl! static members in the class and !ou don@t need to instantiate it. 6hew lost 4n!thing left in constructors; 8es" 7tatic Constructors. %aSS Cow" what are the!; Let us see..

Static Constructors
This is a new concept introduced in C#. A! new here" I mean that it was not available for the CEE developers. This is a special constructor and gets called before the first object is created of the class. The time of execution cannot be determined" but it is definitel! before the first object creation could be at the time of loading the assembl!. The s!ntax of writing the static constructors is also damn simple. %ere it is( Collapse Cop! Code
(u+lic class myClass { static myClass() { :: 7nitiali%ation code goes 6ere. :: Can only access static mem+ers 6ere. } :: Bt6er class met6ods goes 6ere }

Cotes for 7tatic Constructors( There can be onl! one static constructor in the class. The static constructor should be without parameters. It can onl! access the static members of the class. There should be no access modifier in static constructor definition. 5k fine" all the above points are fine" but wh! is it like that; Let us go step b! step here. +irstl!" the call to the static method is made b! the CL2 and not b! the object" so we do not need to have the access modifier to it. 7econdl!" it is going to be called b! CL2" who can pass the parameters to it" if re=uired. 7o we cannot have parameteriBed static constructor. Thirdl!" non static members in the class are specific to the object instance. 7o static constructor" if allowed to work on non static members" will reflect the changes in all the object instances" which is impractical. 7o static constructor can access onl! static

members of the class. +ourthl!" overloading needs the two methods to be different in terms of methods definition" which !ou cannot do with 7tatic Constructors" so !ou can have at the most one static constructor in the class. Cow" one =uestion raises here" can we have two constructors as( Collapse Cop! Code
(u+lic class myClass { static myClass() { :: 7nitiali%ation code goes 6ere. :: Can only access static mem+ers 6ere. } (u+lic myClass() { :: Code 'or t6e First my*erivedClass Constructor. } :: Bt6er class met6ods goes 6ere }

This is perfectl! valid" though doesn@t seem to be in accordance with overloading concepts. Aut wh!; Aecause the time of execution of the two methods are different. 5ne is at the time of loading the assembl! and one is at the time of object creation.

Constructors #A@s
Is the constructor mandator! for a class; 8es" it is mandator! to have the constructor in the class and that too should be accessible for the object i.e." it should have a proper access modifier. 7a!" for example" we have onl! private constructor>s* in the class and if we are interested in instantiating the class" i.e." want to create an object of the class" then having onl! private constructor will not be sufficient and in fact it will raise an error. 7o" proper access modifies should be provided to the constructors. #hat if I do not write the constructor; In such case" the compiler will tr! to suppl! the no parameter constructor for !our class" behind the scene. Compiler will attempt this onl! if !ou do not write the constructor for the class. If !ou provide an! constructor >with or without parameters*" then compiler will not make an! such attempt. #hat if I have the constructor public m!?erivedClass>*" but not the public m!AaseClass>*; It will raise an error. If either the no parameter constructor is absent or it is in accessible >sa! it is private*" it will raise an error. 8ou will have to take the precaution here. Can we access static members from the non static >normal* constructors; 8es" we can. There is no such restriction on non static constructors. Aut there is

one on static constructors that it can access onl! static members. (i''erence bet4een O!erater O%erloading and O%erriding? The main difference between overloading and overriding is that in overloading we can use same function name with different parameters for multiple times for different tasks with on a class. and overriding means we can use same name fiunction name with same parameters of the base class in the derived class. this is also called as reusabilit! of code in the programme. o%erloading( same name but different signatures in same class"5verloading is evaluaated at compile time whereas o%erriding( same name and same signature defined in different class.5verriding is evaluated at 2un Time. O%erloading Two or more functions having same name but different siganture>i.e arguements or return t!pes* for eg. we have a function named as area then area>*D"float area>*D"area>float a"float b*D"float area >float a"float b*D O%erriding #hen a function of base class is re defined in the derived class.for eg. base class T area>float a"float b*D U derive class T float area>*D U Process Instance of the application Session Instance of the user accessing the application Coo0ie 9sed for storing small amount of data on client machine. WhatAs the i$!licit na$e o' the !ara$eter that gets !assed into the classA set $ethod? <alue" and it.s datat!pe depends on whatever variable we.re changing.

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