Vous êtes sur la page 1sur 110

1.What is OOPS? OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects.

Each object is nothing but an instance of a class. 2.Write basic concepts of OOPS? Following are the concepts of OOPS and are as follows:. 1.Abstraction. 2.Encapsulation. 3. nheritance. 4.Polymorphism. 3.What is a class? A class is simply a representation of a type of object. t is the blueprint! plan! template that describe the details of an object. 4.What is an object? Object is termed as an instance of a class" and it has its own state" behavior and identity. 5.What is Encapsulation? Encapsulation is an attribute of an object" and it contains all data which is hidden. #hat hidden data can be restricted to the members of that class. $evels are Public"Protected" Private" nternal and Protected nternal. 6.What is Poly orphis ? Polymorphism is nothing butassigning behavior or value in a subclass to something that was already declared in the main class. Simply" polymorphism ta%es more than one form. !.What is "nheritance? nheritance is a concept where one class shares the structure and behavior defined in another class. finheritance applied on one class is called Single nheritance" and if it depends on multiple classes" then it is called multiple nheritance. #.What are anipulators? &anipulators are the functions which can be used in conjunction with the insertion '(() and e*traction '++) operators on an object. E*amples are endl and setw. $.%efine a constructor? ,onstructor is a method used to initiali-e the state of an object" and it gets invo%ed at the time of object creation. .ules forconstructor are:. ,onstructor /ame should be same asclass name. ,onstructor must have no return type. 1&.%efine %estructor? 0estructor is a method which is automatically called when the object ismade ofscope or destroyed. 0estructor name is also same asclass name but with the tilde symbol before the name. 11.What is "nline function? nline function is a techni1ue used by the compilers and instructs to insert complete body of the function wherever that function is used in the program source code. 12.What is a'irtual function? 2irtual function is a member function ofclass and its functionality can be overridden in its derived

class. #his function can be implemented by using a %eyword called virtual" and it can be given during function declaration. 2irtual function can be achieved in ,33" and it can be achieved in , $anguageby using function pointers or pointers to function. 13.What isfrien( function? Friend function is a friend of a class that is allowed to access to Public" private or protected data in that same class. f the function is defined outside the class cannot access such information. Friend can be declared anywhere in the class declaration" and it cannot be affected by access control %eywords li%e private" public or protected. 14.What is function o'erloa(in)? Function overloading is defined as a normal function" but it has the ability to perform different tas%s. t allowscreation of several methods with the same name which differ from each other by type of input and output of the function. E*ample void add'int4 a" int4 b)5 void add'double4 a" double4 b)5 void add'struct bob4 a" struct bob4 b)5 15.What is operator o'erloa(in)? Operator overloading is a function where different operators are applied and depends on the arguments. Operator"6"7 can be used to pass through the function " and it has their own precedence to e*ecute. E*ample: class comple* 8 double real" imag5 public: comple*'double r" double i) : real'r)" imag'i) 89 comple* operator3'comple* a" comple* b)5 comple* operator7'comple* a" comple* b)5 comple*4 operator:'comple* a" comple* b)5 9 a:;.<" b:= 16.What is an abstract class? An abstract class is a class which cannot be instantiated. ,reation of an object is not possible withabstract class " but it can be inherited. An abstract class can contain only Abstract method. 1!.What is a ternary operator? #ernary operator is said to be an operator which ta%es three arguments. Arguments and results are of different data types " and it is depends on the function. #ernary operator is also called asconditional operator. 1#.What is the use of finali*e etho( Finali-e method helps to perform cleanup operations on the resources which are not currently used. Finali-e method is protected " and it is accessible only through this class or by a derived class. 1$.What are (ifferent types of ar)u ents? A parameter is a variable used during the declaration of the function or subroutine and arguments are passed to the function " and it should match with the parameter defined. #here are two types of

Arguments. ,all by 2alue > 2alue passed will get modified only inside the function " and it returns the same value whatever it is passed it into the function. ,all by .eference > 2alue passed will get modified in both inside and outside the functions and it returns the same or different value. 2&.What is super +ey,or(? Super %eyword is used to invo%e overridden method which overrides one of its superclass methods. #his %eyword allows to access overridden methods and also to access hidden members of the superclass. t also forwards a call from a constructor to a constructor in the superclass. 21.What is etho( o'erri(in)? &ethod overriding is a feature that allows sub class to provide implementation of a method that is already defined in the main class. #his will overrides the implementation in the superclass by providing the same method name" same parameter and same return type. 22.What is an interface? An interface is a collection of abstract method. f the class implements an inheritance" and then thereby inherits all the abstract methods of an interface. 23.What is e-ception han(lin)? E*ception is an event that occurs during the e*ecution of a program. E*ceptions can be of any type > .un time e*ception" Error e*ceptions. #hose e*ceptions are handled properly through e*ception handling mechanism li%e try" catch and throw %eywords. 24.What are to+ens? #o%en is recogni-ed by a compiler and it cannot be bro%en down into component elements. ?eywords" identifiers" constants" string literals and operators are e*amples of to%ens. Even punctuation characters are also considered as to%ens > @rac%ets" ,ommas" @races and Parentheses. 25.%ifference bet,een o'erloa(in) an( o'erri(in)? Overloading is static binding whereas Overriding is dynamic binding. Overloading is nothing but the same method with different arguments " and it may or may not return the same value in the same class itself. Overriding is the same method names with same arguments and return types associates with the class and its child class. 26.%ifference bet,een class an( an object? An object is an instance of a class. Objects hold any information " but classes donAt have any information. 0efinition of properties and functions can be done at class and can be used by the object. ,lass can have sub6classes" and an object doesnAt have sub6objects. 2!.What is an abstraction? Abstraction is a good feature of OOPS " and it shows only the necessary details to the client of an object. &eans" it shows only necessary details for an object" not the inner details of an object. E*ample > Bhen you want to switch On television" it not necessary to show all the functions of #2. Bhatever is re1uired to switch on #2 will be showed by using abstract class.

2#.What are access o(ifiers? Access modifiers determine the scope of the method or variables that can be accessed from other various objects or classes. #here are C types of access modifiers " and they are as follows:. Private. Protected. Public. Friend. Protected Friend. 2$.What is seale( o(ifiers? Sealed modifiers are the access modifiers where it cannot be inherited by the methods. Sealed modifiers can also be applied to properties" events and methods. #his modifier cannot be applied to static members. 3&..o, can ,e call the base etho( ,ithout creatin) an instance? Des" it is possible to call the base method without creating an instance. And that method should be". Static method. 0oing inheritance from that class.6Ese @ase ?eyword from derived class. 31.What is the (ifference bet,een ne, an( o'erri(e? #he new modifier instructs the compiler to use the new implementation instead of the base class function. Bhereas" Override modifier helps to override the base class function. 32.What are the 'arious types of constructors? #here are three various types of constructors " and they are as follows:. 6 0efault ,onstructor > Bith no parameters. 6 Parametric ,onstructor > Bith Parameters. ,reate a new instance of a class and also passing arguments simultaneously. 6,opy ,onstructor > Bhich creates a new object as a copy of an e*isting object. 33.What is early an( late bin(in)? Early binding refers to assignment of values to variables during design time whereas late binding refers to assignment of values to variables during run time. 34.What is /this0 pointer? #F S pointer refers to the current object of a class. #F S %eyword is used as a pointer which differentiates between the current object with the global object. @asically" it refers to the current object. 35.What is the (ifference bet,eenstructure an( a class? Structure default access type is public " but class access type is private. A structure is used for grouping data whereas class can be used for grouping data and methods. Structures are e*clusively used for dataand it doesnAt re1uire strict validation " but classes are used to encapsulates and inherit data which re1uires strict validation. 36.What is the (efault access o(ifier in a class? #he default access modifier of a class is Private by default. 3!.What is pure 'irtual function? A pure virtual function is a function which can be overridden in the derived classbut cannot be defined. A virtual function can be declared as Pure by using the operator :G. E*ample 6.

2irtual void function;') !! 2irtual" /ot pure 2irtual void function<') : G !!Pure virtual 3#.What are all the operators that cannot be o'erloa(e(? Following are the operators that cannot be overloaded 6. 1.Scope .esolution ':: ) 2.&ember Selection '.) 3.&ember selection through a pointer to function '.7) 3$.What is (yna ic or run ti e poly orphis ? 0ynamic or .un time polymorphism is also %nown as method overriding in which call to an overridden function is resolved during run time" not at the compile time. t means having two or more methods with the same name"same signature but with different implementation. 4&.%o ,e re1uire para eter for constructors? /o" we do not re1uire parameter for constructors. 41.What is a copy constructor? #his is a special constructor for creating a new object as a copy of an e*isting object. #here will be always only on copy constructor that can be either defined by the user or the system. 42.What (oes the +ey,or( 'irtual represente( in the t means" we can override the method. 43.Whether static False. etho( can use non static e bers? etho( (efinition?

44.What arebase class2 sub class an( super class? @ase class is the most generali-ed class " and it is said to be a root class.Sub class is a class that inherits from one or more base classes.Super class is the parent class from which another class inherits. 45.What is static an( (yna ic bin(in)? @inding is nothing but the association of a name with the class. Static binding is a binding in which name can be associated with the class during compilation time " and it is also called as early @inding.0ynamic binding is a binding in which name can be associated with the class during e*ecution time " and it is also called as $ate @inding. 46..o, any instances can be create( for an abstract class? Hero instances will be created for an abstract class. 4!.Which +ey,or( can be use( for o'erloa(in)? Operator %eyword is used for overloading. 4#.What is the (efault access specifier in a class (efinition? Private access specifier is used in a class definition. 4$.Which OOPS concept is use( as reuse echanis ? nheritance is the OOPS concept that can be used as reuse mechanism. 5&.Which OOPS concept e-poses only necessary infor ation to the callin) functions? %ata .i(in) 3 4bstraction

4bstraction
Abstraction refers to the act of representing essential features without including the bac%ground details or e*planations. Abstraction defines way to abstract or hide your data and members from outside world. ,lasses use the concept of abstraction and are defined as a list of abstract attributes. Simply spea%ing Abstraction is hiding the comple*ities of your class or struct or in a generic term #ype from outer world. #his is achieved by means of access specifiers. 4ccess 5o(ifier %escription 6,ho can access7 Private Only members within the same type. 'default for type members) Protected Only derived types or members of the same type. Only code within the same assembly. ,an also be code e*ternal to nternal object as long as it is in the same assembly. 'default for types) Either code from derived type or code in the same assembly. Protected internal ,ombination of protected O. internal. Any code. /o inheritance" e*ternal type" or e*ternal assembly Public restrictions. 8o(e E-a ple 9 namespace AbstractionE*ample 8 public abstract class Shape 8 private float Iarea5 private float Iperimeter5 public float Area 8 get 8 return Iarea5 9 set 8 Iarea : value5 9 9 public float Perimeter 8 get 8 return Iperimeter5 9 set 8 Iperimeter : value5 9 9 public abstract void ,alculateArea')5 public abstract void ,alculatePerimeter')5 9 9 Advantages of abstraction are the hiding of implementation details" component reuse" e*tensibility" and testability. Bhen we hide implementation details" we reveal a cleaner" more comprehensible and usable interface to our users. Be are separating our interface from our implementation" and this ma%es component reuse more practical. &any" if not all of the object6oriented concepts we have discussed throughout this document play a role in the abstraction principle. Bor%ing together" their end goal is the same" to produce software that is fle*ible" testable" maintainable" and e*tensible. %efinition Abstraction is one of the principle of object oriented programming. t is used to display only necessary and essential features of an object to ouside the world.&eans displaying what is necessary and encapsulate the unnecessary things to outside the world.Fiding can be achieved by using JprivateJ access modifiers. :ote 6 Outside the world means when we use reference of object then it will show only necessary methods and properties and hide methods which are not necessary. mplementation of Abstraction

#o implement abstraction letKs ta%e an e*ample of a car. Be %nows a car" ,ar is made of name of car" color of car" steering" gear" rear view mirror" bra%es" silencer" e*haust system" diesal engine" car battery" car engine and other internal machine details etc. /ow lets thin% in terms of ,ar rider or a person who is riding a car. So to drive a car what a car rider should %now from above category before he starts a car driving. /ecessary things means compulsary to %now before starting a car ;. /ame of ,ar <. ,olor of ,ar L. Steering M. .ear 2iew &irror C. @ra%es =. Near Ennecessary things means not that compulsary to %now for a ,ar rider ;. nternal 0etails of a ,ar <. ,ar Engine L. 0iesal Engine M. E*haust System C. Silencer public class ,ar
private string _nameofcar = "My Car"; private string _colorofcar = "Red"; public string NameofCar set } get } } public string ColorofCar set } get } } public void Steering( } Console!"rite#ine("Streering of Car" ; _colorofcar = value; _nameofcar = value;

return _nameofcar;

return _colorofcar;

public void Rear$ie%Mirror( Console!"rite#ine("Rear$ie%Mirror of Car" ; } public void &ra'es( Console!"rite#ine("&ra'es of Car" ; } public void (ear( } Console!"rite#ine("(ear of Car" ;

private void )nternal*etailsofCar( } Console!"rite#ine(")nternal*etailsofCar of Car" ;

private void Car+ngine( Console!"rite#ine("Car+ngine of Car" ; } private void *iesal+ngine( } Console!"rite#ine("*iesal+ngine of Car" ;

private void +,-austSystem( Console!"rite#ine("+,-austSystem of Car" ; } private void Silencer( } } Console!"rite#ine("Silencer of Car" ;

Encapsulation
Encapsulation is way to hide data" properties and methods from outside the world or outside of the class scope and e*posing only necessary thing.Encapsulation complements Abstraction. Abstraction display only important features of a class and Encapsulation hides unwanted data or private data from outside of a class. t hides the information within the object and prevents from accidental corruption. .o, ,e can achie'e Encapsulation Be can achieve Encapsulation by using JprivateJ access modifier as shown in below snippet of code. class Employee8
private void .ccount)nformation( / Console!"rite#ine("*isplaying .ccount *etails" ; } }

Bhy to use Encapsulation Encapsulation means protecting important data inside the class which we do not want to be e*posed outside of the class.$ets consider e*ample of a #elevision'#2). f you have seen important #2 machine" #2 connections and #2 color tube is hidden inside the #2 case which is not been e*posed for viewers li%e us and e*posed only neccessary things of a #2 li%e #2 ,hannel %eys" #2 volume %eys" O/!OFF switch" ,able Switch and #2 remote control for viewers to use it.#his means #2 machine" #2 connections and #2 color tube is an unwanted data and not needed for viewers to see is been hidden from outside the world.So encapsulation means hiding the important features of a class which is not been needed to be e*posed outside of a class and e*posing only necessary things of a class.Fere hidden part of a class acts li%e Encapsulation and e*posed part of a class acts li%e Abstraction.
class cls0elevision/ private void 0$mac-ine( / Console!"rite#ine("Mac-ine of a 0elevision" ; } private void 0$colortube( / Console!"rite#ine("Color 0ube of a 0elevision" ; } public void 0$1eys( / Console!"rite#ine("1eys of a 0elevision" ;

public void 0$Remote( / Console!"rite#ine("Remote of a 0elevision" ; } public void 0$Screen( / Console!"rite#ine(""ide Screen of a 0elevision" ; }}

#he following are the benefits of encapsulation: Protection of data from accidental corruption Specification of the accessibility of each of the members of a class to the code outside the class Fle*ibility and e*tensibility of the code and reduction in comple*ity $ower coupling between objects and hence improvement in code maintainability. ;echope(ia e-plains Encapsulation Encapsulation in ,O is implemented with different levels of access to object data that can be specified using the following access modifiers: Public: Access to all code in the program Private: Access to only members of the same class Protected: Access to members of same class and its derived classes nternal: Access to current assembly Protected nternal: Access to current assembly and types derived from containing class

Abstraction Abstraction solves the problem in the design level. Abstraction is used for hiding the unwanted data and giving only relevant data.

Encapsulation Encapsulation solves the problem in the implementation level. Encapsulation is hiding the code and data into a single unit to protect the data from outer world.

Abstraction is set focus on the object instead of Encapsulation means hiding the internal details or mechanics of how an how it does it. object does something. Abstraction is outer layout in terms of design. For E*ample: 6 Outer $oo% of a iPhone" li%e it has a display screen. Encapsulation is inner layout in terms of implementation. For E*ample: 6 nner mplementation detail of a iPhone" how 0isplay Screen are connect with each other using circuits

Difference between Encapsulation and Abstraction in OOPS Abstraction and Encapsulation are two important Object Oriented Programming (OOPS) concepts. Encapsulation and Abstraction both are interrelated terms. Real Life Difference Between Encapsulation and Abstraction Encapsulate means to hide. Encapsulation is also called data hiding.You can think Encapsulation like a capsule (medicine tablet) which hides medicine inside it. Encapsulation is wrapping, just hiding properties and methods. Encapsulation is used or hide the code and data in a single unit to protect the data rom the outside the world. !lass is the best e"ample o encapsulation. Abstraction re ers to showing onl# the necessar# details to the intended user. As the name suggests, abstraction is the $abstract orm o an#thing$. %e use abstraction in programming languages to make abstract class. Abstract class represents abstract &iew o methods and properties o class. Implementation Difference Between Encapsulation and Abstraction 1. Abstraction is implemented using inter ace and abstract class while Encapsulation is implemented using

pri&ate and protected access modi ier. 2. OOPS makes use o encapsulation to en orce the integrit# o a t#pe (i.e. to make sure data is used in an appropriate manner) b# pre&enting programmers rom accessing data in a non'intended manner. (hrough encapsulation, onl# a predetermined group o unctions can access the data. (he collecti&e term or datat#pes and operations (methods) bundled together with access restrictions (public)pri&ate, etc.) is a class. . E!ample of Encapsulation !lass Encapsulation * pri&ate int marks+ public int ,arks * get * return marks+ set * marks . &alue+". E!ample of Abstraction abstract class Abstraction * public abstract &oid doAbstraction()+ public class Abstraction/mpl0 Abstraction * public &oid doAbstraction() * ))/mplement it -

4bstract 8lass
An abstract class cannot be instantiated. #he purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For e*ample" a class library may define an abstract class that is used as a parameter to many of its functions" and re1uire programmers using that library to provide their own implementation of the class by creating a derived class. Abstract classes may also define abstract methods. #his is accomplished by adding the %eyword abstract before the return type of the method. Abstract classes are one of the essential behaviors provided by ./E#. ,ommonly" you would li%e to ma%e classes that only represent base classes" and donAt want anyone to create objects of these class types. Dou can ma%e use of abstract classes to implement such functionality in ,O using the modifier KabstractK. An abstract class means that" no object of this class can be instantiated" but can ma%e derivations of this. An abstract class can contain either abstract methods or non abstract methods. Abstract members do not have any implementation in the abstract class" but the same has to be provided in its derived class.
abstract class absClass { public abstract void abstractMethod(); }

Also" note that an abstract class does not mean that it should contain abstract members. Even we can have an abstract class only with non abstract members. For e*ample:
abstract class absClass { public void NonAbstractMethod() { Console.WriteLine("NonAbstract Method"); } }

A sample program that explains abstract classes:


using !ste";

na"espace abstract a"ple { //Creating an Abstract Class abstract class absClass { //A Non abstract method public int Add#$oNu"bers(int Nu"%& int Nu"') { return Nu"% ( Nu"'; } //An abstract method, to be //overridden in derived class

public abstract int Multipl!#$oNu"bers(int Nu"%& int Nu"'); } //A Child Class of absClass class abs)erived*absClass { + #A#hread, static void Main(string+, args) { //You can create an //instance of the derived class abs)erived calculate - ne$ abs)erived(); int added - calculate.Add#$oNu"bers(%.&'.); int "ultiplied - calculate.Multipl!#$oNu"bers(%.&'.); Console.WriteLine("Added * {.}& Multiplied * {%}"& added& "ultiplied); } //using override keyword, //implementing the abstract method //MultiplyTwoNumbers public override int Multipl!#$oNu"bers(int Nu"%& int Nu"') { return Nu"% / Nu"'; } } }

n the above sample" you can see that the abstract class abs,lass contains two methods Add#wo/umbers and&ultiply#wo/umbers. Add#wo/umbers is a non6abstract method which contains implementation and&ultiply#wo/umbers is an abstract method that does not contain implementation. #he class abs0erived is derived from abs,lass and the &ultiply#wo/umbers is implemented on abs0erived. Bithin the &ain" an instance 'calculate) of the abs0erived is created" and calls Add#wo/umbers and&ultiply#wo/umbers. Dou can derive an abstract class from another abstract class. n that case" in the child class it is optional to ma%e the implementation of the abstract methods of the parent class. //Abstract Class1
abstract class absClass% { public abstract int Add#$oNu"bers(int Nu"%& int Nu"'); public abstract int Multipl!#$oNu"bers(int Nu"%& int Nu"'); } //Abstract Class abstract class absClass'*absClass% { //!mplementing AddTwoNumbers public override int Add#$oNu"bers(int Nu"%& int Nu"') { return Nu"%(Nu"'; }

} //"erived class from absClass class abs)erived*absClass' { //!mplementing MultiplyTwoNumbers public override int Multipl!#$oNu"bers(int Nu"%& int Nu"') { return Nu"%/Nu"'; } }

In the above e*ample" abs,lass; contains two abstract methods Add#wo/umbers and &ultiply#wo/umbers. #heAdd#wo/umbers is implemented in the derived class abs,lass<. #he class abs0erived is derived from abs,lass<and the &ultiply#wo/umbers is implemented there.

Abstract properties
Following is an example of implementing abstract properties in a class.
//Abstract Class with abstract properties abstract class absClass { protected int "!Nu"ber; public abstract int nu"bers { get; set; } } class abs)erived*absClass { //!mplementing abstract properties public override int nu"bers { get { return "!Nu"ber; } set { } } } "!Nu"ber - value;

n the above e*ample" there is a protected member declared in the abstract class.#he get!set properties for the member variable my/umber is defined in the derived class abs0erived. mportant rules applied to abstract classes
An abstract class cannot be a sealed class. I.e. the following declaration is incorrect.
//!ncorrect

abstract sealed class absClass { }

Declaration of abstract methods are only allowed in abstract classes. An abstract method cannot be private.
//!ncorrect private abstract int Multipl!#$oNu"bers();

The access modifier of the abstract method should be same in both the abstract class and its derived class. If you declare an abstract method as protected, it should be protected in its derived class. therwise, the compiler will raise an error. An abstract method cannot have the modifier virtual. !ecause an abstract method is implicitly virtual.
//!ncorrect public abstract virtual int Multipl!#$oNu"bers();

An abstract member cannot be static.


//!ncorrect publpublic abstract static int Multipl!#$oNu"bers();

Abstract class vs. nterface


An abstract class can have abstract members as well non abstract members. !ut in an interface all the members are implicitly abstract and all the members of the interface must override to its derived class. An example of interface:
inter0ace i a"ple1nter0ace { //All methods are automaticall abstract int AddNu"bers(int Nu"%& int Nu"'); int Multipl!Nu"bers(int Nu"%& int Nu"'); }

Defining an abstract class with abstract members has the same effect to defining an interface. The members of the interface are public with no implementation. Abstract classes can have protected parts, static methods, etc. A class can inherit one or more interfaces, but only one abstract class. Abstract classes can add more functionality without destroying the child classes that were using the old version. In an interface, creation of additional functions will have an effect on its child classes, due to the necessary implementation of interface methods to classes. The selection of interface or abstract class depends on the need and design of your pro"ect. #ou can ma$e an abstract class, interface or combination of both depending on your needs.

4bstract 5etho( n an abstract class a method which has a %eyword JabstractJ and doesnKt provide any implementation is called abstract method.#he implementation logic of abstract methods is provided by the child classes or derived classes.,hild classes use %eyword JoverrideJ with same method name 'as abstract method name) to provide further implementation of abstract methods. :on 4bstract 5etho( n an abstract class a method which doesnKt have a %eyword JabstractJ and provide any

implementation is called non abstract method. Why 4bstract 8lass Abstract class enforces derived classes to provide all implementation logic for abstract methods or properties. <se of an 4bstract 8lass Ese abstract class when you want to create a common base class for a family of types and with some implementation Subclass only a base class in a hierarchy to which the class logically belongs.
#he purpose of abstract class is to provide default functionality to its sub classes. Bhen a method is declared as abstract in the base class then every derived class of that class must provide its own definition for that method. An abstract class can also contain methods with complete implementation" besides abstract methods. Bhen a class contains at least one abstract method" then the class must be declared as abstract class . t is an(atory to override abstract method in the derived class.

Bhen a class is declared as abstract class" then it is not possible to create an instance for that class. @ut it can be used as a parameter in a method.

4bstract etho(9 Bhen a class contains an abstract method" that class must be declared as abstract. #he abstract method has no implementation and thus" classes that derive from that abstract class" must provide an implementation for this abstract method. =irtual etho(9 A class can have a virtual method. #he virtual method has an implementation. Bhen you inherit from a class that has a virtual method" you can override the virtual method and provide additional logic" or replace the logic with your own implementation. When to use ,hat9 n some cases" you %now that certain types should have a specific method" but" you donKt %now what implementation this method should have. n such cases" you can create an interface which contains a method with this signature. Fowever" if you have such a case" but you %now that implementors of that interface will also have another common method 'for which you can already provide the implementation)" you can create an abstract class. #his abstract class then contains the abstract method 'which must be overriden)" and another method which contains the KcommonK logic. A virtual method should be used if you have a class which can be used directly" but for which you want inheritors to be able to change certain behaviour" although it is not mandatory.
<se of :on 4bstract 5etho( of 4bstract 8lass in 8> Dou can have non abstract method in abstract class5 as such didnAt find any use of these methods. Des this is an option. &ay be it is useful in some situations when you want to call those methods inside your abstract methods.

As per abstraction rules" you cannot create the object of abstract class" means you cannot use the"ne%" %eyword. Dou can create any class as an abstract class with the help of PAbstract %eyword5 even you can create any method as an abstract method inside the class. Abstract class can have both type of method PAbstract & Non Abstract. Dou can inherit these classes inside the non abstract classes. Abstract classes cannot have the implementations details of abstract methods.
4bstract 8lasses An Abstract class is used when there is a common unctionalit# to be shared between the subclasses,

but the superclass itsel will ne&er e"ist. 1or e"ample, a class 2erson will ne&er e"ist. 2owe&er a class Wo"an will. /nstead o repeating all the methods that are in Wo"an, in Man, 3o! and 4irl, we simpl# raise it to the superclass, so the# all ha&e access to this unctionalit#, and can o&erride the methods that the# want to per orm di erentl#. Interfaces /nter aces are used when there is a re3uirement. (he wa# / look at them is like a contract. (he agreement being that an# class that implements the /nter ace, will ha&e to pro&ide code or a certain number o methods. 1or e"ample, A class 5oc6 and a class 3all can both be thrown. /nstead o the method to throw a ball ha&ing to take into account e&er# object that can be thrown, i e&er# object /mplements the #hro$ing1te" /nter ace (/ didn4t want to use the word #hro$able or ob&ious reasons), then the method can just accept an object o t#pe #hro$ing1te" and knows or a act that the agreed methods will be there. (his enables loose coupling between the thro$ method and the classes that use it, because all communication is done through the inter ace.

f you have a type that can be designed as either an interface or an abstract class" why would you choose abstract classQ n that sense" we only use abstract class when some features cannot be done in interface: ;.state. though an interface could as% subclasses to implement state" it might be more convenient to use an abstract super class to hold the state.

<.restricting member access to protected. while all things in interface are public
L.static methods. 'note that in Rava S" probably" interface can have static methods) M.concrete methods with implementations. 'note that in Rava S" interface methods can have defualt impl) C.add more concrete methods without brea%ing subclasses. 'note that in Rava S" we can add more methods to an e*isting interface if the methods have default impls)

=irtual 5etho(s in 8>.:E; ,ith e-a ple Bhen you want to allow a derived class to override a method of the base class" within the base class method must be created as virtual method and within the derived class method must be created using the %eyword override. Bhen a method declared as virtual in base class" then that method can be defined in base class and it is optional for the derived class to override that method. Bhen it needs same definition as base class" then no need to override the method and if it needs different definition than provided by base class then it must override the method. &ethod overriding also provides more than one form for a method. Fence it is also an e*ample for polymorphism. ;he follo,in) e-a ple creates three classes shape2 circle an( rectan)le ,here circle an(

rectan)le are inherite( fro the class shape an( o'erri(es the 8ircu ference67 that are (eclare( as 'irtual in Shape class.
using System5 namespace Program,all 8 class Shape 8 protected float ." $" @5 public virtual float Area') 8 return L.;MF 7 . 7 .5 9 public virtual float ,ircumference') 8 return < 7 L.;MF 7 .5 9 9 class .ectangle : Shape 8 public void Net$@') 8 ,onsole.Brite'JEnter $ength : J)5 $ : float.Parse',onsole..ead$ine'))5 ,onsole.Brite'JEnter @readth : J)5 @ : float.Parse',onsole..ead$ine'))5 9 public override float Area') 8 return $ 7 @5 9 public override float ,ircumference') 8 return < 7 '$ 3 @)5 9 9 class ,ircle : Shape 8 public void Net.adius') 8 ,onsole.Brite'JEnter .adius : J)5 . : float.Parse',onsole..ead$ine'))5 9 9

etho(s 4rea67 an(

class &ain,lass 8 static void &ain') 8 .ectangle . : new .ectangle')5 ..Net$@')5 ,onsole.Brite$ine'JArea : 8G9J" ..Area'))5 ,onsole.Brite$ine'J,ircumference : 8G9J" ..,ircumference'))5 ,onsole.Brite$ine')5 ,ircle , : new ,ircle')5 ,.Net.adius')5 ,onsole.Brite$ine'JArea : 8G9J" ,.Area'))5 ,onsole.Brite$ine'J,ircumference : 8G9J" ,.,ircumference'))5 ,onsole..ead')5 9 9

A virtual method is a method that can be redefined in derived classes. A virtual method has an implementation in a base class as well as derived the class. t is used when a methodKs basic functionality is the same but sometimes more functionality is needed in the derived class. A virtual method is created in the base class that can be overriden in the derived class. Be create a virtual method in the base class using the virtual %eyword and that method is overriden in the derived class using the override %eyword. Bhen a method is declared as a virtual method in a base class then that method can be defined in a base class and it is optional for the derived class to override that method. #he overriding method also provides more than one form for a method. Fence it is also an e*ample for polymorphism. Bhen a method is declared as a virtual method in a base class and that method has the same definition in a derived class then there is no need to override it in the derived class. @ut when a virtual method has a different definition in the base class and the derived class then there is a need to override it in the derived class. Bhen a virtual method is invo%ed" the run6time type of the object is chec%ed for an overriding member. #he overriding member in the most derived class is called" which might be the original member" if no derived class has overridden the member.
Virtual Method %.!y default, methods are non&virtual. 'e can(t override a non&virtual method. ).'e can(t use the virtual modifier with the static, abstract, private or override modifiers.

5etho( O'erri(in) in 8>.:E; ,reating a method in derived class with same signature as a method in base class is called as method overriding.

Same signature means methods must have same name, same number of arguments and same type of arguments. Method overriding is possible only in derived classes, but not within the same class. When derived class needs a method with same signature as in base class, but wants to execute different code than provided by base class then method overriding will be used. To allow the derived class to override a method of the base class, C# provides two options,virtual methods and abstract methods. xamples for Method !verriding in C# using System5 namespace methodoverriding 8 class @ase,lass 8 public virtual string Dour,ity') 8 return J/ew Dor%J5 9 9 class 0erived,lass : @ase,lass

8 public override string Dour,ity') 8 return J$ondonJ5 9 9 class Program 8 static void &ain'stringTU args) 8 0erived,lass obj : new 0erived,lass')5 string city : obj.Dour,ity')5 ,onsole.Brite$ine'city)5 ,onsole..ead')5 9 9 9 Output $ondon E*ample 6 < implementing abstract method using System5 namespace methodoverridinge*ample 8 abstract class @ase,lass 8 public abstract string Dour,ity')5 9 class 0erived,lass : @ase,lass 8 public override string Dour,ity') 8 return J$ondonJ5 9 private int sum'int a" int b) 8 return a 3 b5 9 9 class Program 8 static void &ain'stringTU args) 8 0erived,lass obj : new 0erived,lass')5 string city : obj.Dour,ity')5 ,onsole.Brite$ine'city)5 ,onsole..ead')5 9 9 9 Output $ondon

!! t is mandatory to implement absract method

"nterface
An interface loo%s li%e a class but has got no implementation. n an interface we cannot do any implementation but we can declare signatures of properties" methods" delegates and events. mplementation part is been handle by the class that implements the interface. mplemented interface enforces the class li%e a standard contract to provide all implementation of interface members. Be can implement single interface or multiple interfaces to the class. @y default interfaces are public. Be declare interface by using JinterfaceJ %eyword.
interface )+mployee/ void *isplay+mployee*etails( ; }

Above synta* shows simple demonstration of interface J EmployeeJ with signature of a method J0isplayEmployee0etailsJ. /ow letKs implement the same interface to a class.
class clsEmployee : Employee / public void *isplay+mployee*etails( / Console!"rite#ine(2*isplaying employee details34 ; } }

?enefits of usin) an interface mplemented interface enforces the class li%e a standard contract to provide all implementation of interface members. n architecting the project we can define the proper naming conventions of methods" properties in an interface so that while implementing in a class we use the name conventions. Be can use the JinterfaceJ as a pointer in the different layers of applications.Be can use an interface for implementing run time polymorphism. =arious @or s of i ple entin) interface #here are two of ways of implementing interfaces E*plicit mplicit E-plicit interface i ple entation #o implement an interface e*plicitly we have to define an interface name followed by 'J.J) dot operator then the method name. public class Employee : Employee
/ void )+mployee!*isplay+mployee*etails( / Console!"rite#ine(")+mployee +mployee Name 556!!!!!" ; }

"n ,hich scenario ,e use e-plicit interface i ple entation Bhen we have two different interfaces with same method name then in that scenario we can use e*plicit interface implementation. E*ample of E*plicit nterface
public interface Employee8 void *isplay+mployee*etails( ; } public interface )Company/ void *isplay+mployee*etails( ; }

n order to implement an interface e*plicitly we have to define the interface name followed by 'A.A) dot operator before method name as shown in below snipped code.
public class Employee : Employee" ,ompany 8 void ,ompany.0isplayEmployee0etails')8 ,onsole.Brite$ine'J ,ompany Employee /ame 66+ Vuestpond and Employee ,ode 66+ GGWJ)5 9 void Employee.0isplayEmployee0etails')8 ,onsole.Brite$ine'J Employee Employee /ame 66+ Vuestpond and Employee ,ode 66+ GGWJ)5 9 9

Properties Of "nterface9B Supports multiple inheritance'Single ,lass can implement multiple interfaces). ,ontains only incomplete method. ,an not ,ontains data members. @y 0efault interface members is public 'Be ,an not set any access modifier into interface members). nterface can not contain constructors. hide implementation details of classes from each other facilitate reuse of software "nterface characteristics in the Cco(e ,orl(D An iterface defines only the properties and method signatures and not the actual implementation. mean that in a class declaration we implement fields"properties"methods and events. n an interface we just define what properties!methods the class should have. .e1uires that classes which implement an interface must XhonourX the property and method signatures. @asically are li%e contracts for classes. ,lasses which implement an interface must implement the methods and the properties of the interface. &any classes can implement a particular interface method" in their own way. An interface may inherit from multiple base interfaces. A class may implement6inherit from multiple interfaces. A ,O class may only inherit from one class.

Feature &ultiple inheritance 0efault implementation

nterface A class may inherit several interfaces. An interface cannot provide any code" just the signature. An interface cannot have access modifiers for the subs" functions" properties etc everything is assumed as public nterfaces are used to define the peripheral abilities of a class. n other words both Fuman and 2ehicle can inherit from a &ovable interface. f various implementations only share method signatures then it is better to use nterfaces. .e1uires more time to find the actual method in the corresponding classes. f we add a new method to an nterface then we have to trac% down all the implementations of the interface and define implementation for the new method. /o fields can be defined in interfaces

Abstract class A class may inherit only one abstract class. An abstract class can provide complete" default code and!or just the details that have to be overridden. An abstract class can contain access modifiers for the subs" functions" properties An abstract class defines the core identity of a class and there it is used for objects of the same type.

Access &odfiers

,ore 2S Peripheral

Fomogeneity

f various implementations are of the same %ind and use common behaviour or status then abstract class is better to use. Fast

Speed

Adding functionality '2ersioning)

f we add a new method to an abstract class then we have the option of providing default implementation and therefore all the e*isting code might wor% properly. An abstract class can have fields and constrants defined

Fields and ,onstants

Poly orphis in 8>.:E; According to &S0/" #hrough inheritance" a class can be used as more than one type5 it can be used as its own type" any base types" or any interface type if it implements interfaces. #his is called polymorphism. n ,O" every type is polymorphic. #ypes can be used as their own type or as a Object instance" because any type automatically treats Object as a base type. Polymorphism means having more than one form. Overloading and overriding are used to implement polymorphism. Polymorphism is classified into compile time polymorphism or early binding or static binding and .untime polymorphism or late binding or dynamic binding Polymorphism E*amples 5etho( O'erloa(in) 5etho( O'erri(in) ,ompile time Polymorphism or Early @inding #he polymorphism in which compiler identifies which polymorphic form it has to e*ecute at compile time it self is called as compile time polymorphism or early binding. Advantage of early binding is e*ecution will be fast. @ecause every thing about the method is %nown to compiler during compilation it self and disadvantage is lac% of fle*ibility. E*amples of early binding are overloaded methods" overloaded operators and overridden methods that are called directly by using derived objects. .untime Polymorphism or $ate @inding #he polymorphism in which compiler identifies which polymorphic form to e*ecute at runtime but not at compile time is called as runtime polymorphism or late binding. Advantage of late binding is fle*ibility and disadvantage is e*ecution will be slow as compiler has to get the information about the method to e*ecute at runtime. E*ample of late binding is overridden methods that are called using base class object.

Static 8lass
A static class is basically the same as a non6static class" but there is one difference: a static class cannot be instantiated. n other words" you cannot use the new %eyword to create a variable of the class type. @ecause there is no instance variable" you access the members of a static class by using the class name itself. For e*ample" if you have a static class that is named Etility,lass that has a public method named &ethodA" you call the method as shown in the following e*ample:
Etility,lass.&ethodA')5

A static class can be used as a convenient container for sets of methods that just operate on input parameters and do not have to get or set any internal instance fields. For e*ample" in the ./E# Framewor% ,lass $ibrary" the static System.&ath class contains methods that perform mathematical operations" without any re1uirement to store or retrieve data that is uni1ue to a particular instance of the &ath class. #hat is" you apply the members of the class by specifying the class name and the method name" as shown in the following e*ample.
double dub : 6L.;M5 Console.WriteLine(Math.Abs(dub)); Console.WriteLine(Math.7loor(dub)); Console.WriteLine(Math.5ound(Math.Abs(dub))); 88 88 88 88 9utput* :.%; <; :

As is the case with all class types" the type information for a static class is loaded by the ./E# Framewor% common language runtime ',$.) when the program that references the class is loaded. #he program cannot specify e*actly when the class is loaded. Fowever" it is guaranteed to be loaded and to have its fields initiali-ed and its static constructor called before the class is referenced for the first time in your program. A static constructor is only called one time" and a static class remains in memory for the lifetime of the application domain in which your program resides. #he following list provides the main features of a static class: ,ontains only static members. ,annot be instantiated. s sealed. ,annot contain nstance ,onstructors. ,reating a static class is therefore basically the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated. #he advantage of using a static class is that the compiler can chec% to ma%e sure that no instance members are accidentally added. #he compiler will guarantee that instances of this class cannot be created. Static classes are sealed and therefore cannot be inherited. #hey cannot inherit from any class e*cept Object. Static classes cannot contain an instance constructor5 however" they can contain a static constructor. /on6static classes should also define a static constructor if the class contains static members that re1uire non6trivial initiali-ation. For more information" see Static ,onstructors ',O Programming Nuide).

public

static class #emperature,onverter { public static double Celsius#o7ahrenheit(string te"peratureCelsius) { 88 Convert argu"ent to double 0or calculations. double celsius - )ouble.2arse(te"peratureCelsius); 88 Convert Celsius to 7ahrenheit. double 0ahrenheit - (celsius / = 8 >) ( :'; return 0ahrenheit; } public static double 7ahrenheit#oCelsius(string te"perature7ahrenheit) { 88 Convert argu"ent to double 0or calculations. double 0ahrenheit - )ouble.2arse(te"perature7ahrenheit); 88 Convert 7ahrenheit to Celsius. double celsius - (0ahrenheit < :') / > 8 =; return celsius; } } class #est#e"peratureConverter { static void Main() { Console.WriteLine("2lease select the convertor direction"); Console.WriteLine("%. 7ro" Celsius to 7ahrenheit."); Console.WriteLine("'. 7ro" 7ahrenheit to Celsius."); Console.Write("*"); string selection - Console.5eadLine(); double 7& C - .; s$itch (selection) { case "%"* Console.Write("2lease enter the Celsius te"perature* "); 7 - #e"peratureConverter.Celsius#o7ahrenheit(Console.5eadLine()); Console.WriteLine("#e"perature in 7ahrenheit* {.*7'}"& 7); brea6; case "'"* Console.Write("2lease enter the 7ahrenheit te"perature* "); C - #e"peratureConverter.7ahrenheit#oCelsius(Console.5eadLine()); Console.WriteLine("#e"perature in Celsius* {.*7'}"& C); brea6; de0ault* Console.WriteLine("2lease select a convertor."); brea6; } 88 ?eep the console $indo$ open in debug "ode. Console.WriteLine("2ress an! 6e! to e@it."); Console.5ead?e!(); } }

Static you can use the method of the class which is static, but you ma"e sure that the value gets changed as you re#uired. $f you are using the class and ob%ect concept it means that you are using the !!&S concepts. Static class is used when you are aware of that the value that you are going to use in entire application will remain same means that at one place you will set the value and from other place you will get that value, at that point of time it's better to use static class.

The following are rules to create a static class: Rule#1. a static class must contain the static $eyword in the class declaration. Eule>2. a method should be static i.e. the method declaration must contain the static %eyword. Eule>3. the ,onstructor must be static because a static class doesnKt allow an instance constructor. Eule>4. the ,onstructor must not contain an access modifier. Eule>5. a Static class canKt implement an inteface. Eule>6. a Static class canKt be a base class i.e. it cannot be derived from. s a class whose members must be accessed without an instance of the class. n other words" the members of a static class must be accessed directly from 'using the name of) the class" using the period operator 1s a class $hose "e"bers "ust be created as static. 1n other $ords& !ou cannot add a non<static "e"ber to a static class* all "e"bers& e@cept 0or constants& "ust be static

Static 5e ber A non6static class can contain static methods" fields" properties" or events. #he static member is callable on a class even when no instance of the class has been created. #he static member is always accessed by the class name" not the instance name. Only one copy of a static member e*ists" regardless of how many instances of the class are created. Static methods and properties cannot access non6static fields and events in their containing type" and they cannot access an instance variable of any object unless it is e*plicitly passed in a method parameter. t is more typical to declare a non6static class with some static members" than to declare an entire class as static. #wo common uses of static fields are to %eep a count of the number of objects that have been instantiated" or to store a value that must be shared among all instances. Static methods can be overloaded but not overridden" because they belong to the class" and not to any instance of the class. Although a field cannot be declared as static const" a const field is essentially static in its behavior. t belongs to the type" not to instances of the type. #herefore" const fields can be accessed by using the same ,lass/ame.&ember/ame notation that is used for static fields. /o object instance is re1uired. ,O does not support static local variables 'variables that are declared in method scope). Dou declare static class members by using the static %eyword before the return type of the member" as shown in the following e*ample:
public class Auto"obile { public static int Nu"ber90Wheels - ;; public static int iAe904as#an6 { get { return %>; }

} public static void )rive() { } public static event Bvent#!pe 5un9ut904as; 88 9ther non<static 0ields and properties... }

Static 5etho(9B Static etho(s have no instances. #hey are called with the type name" not an instance identifier. #hey are slightly faster than instance methods because of this. Static methods can be public or private.
A static unction, unlike a regular (instance) unction, is not associated with an instance o the class. A static class is a class which can onl# contain static members, and there ore cannot be instantiated. 1or e"ample0 class o"eClass { public int 1nstanceMethod() { return %; } public static int taticMethod() { return ;'; } } /n order to call 1nstanceMethod, #ou need an instance o the class0 o"eClass instance - ne$ o"eClass(); instance.1nstanceMethod(); 887ine instance. taticMethod(); 88WonCt co"pile o"eClass.1nstanceMethod(); o"eClass. taticMethod(); 88WonCt co"pile 887ine

#he static %eyword" when applied to a class" tells the compiler to create a single instance of that class. t is not then possible to KnewK one or more instance of the class. All methods in a static class must themselves be declared static. t is possible" And often desirable" to have static methods of a non6static class. For e*ample a factory method when creates an instance of a nother class is often declared static as this means that a particular instance of the class containing the factor method is not re1uired. Static %eyword is widely used to share the same field or method among all the objects of the class. #he actual goal of the static %eyword is to share a single data over all the objects. #here are three types of sharing using the static %eyword. #hey are: Static &ethod Static Field Static ,lass /ow am going to give a short brief on these three types. Static 5etho( A static method can be accessed from outside the class without creating any object of this class. #his staticmethod can be accessed directly by the name of the static method followed by the . 'dot operator) and the class name. For e*ample" we can consider the S1rt method of the &ath class. #his is how the S1rt method of the real &athclass is defined :

class &ath 8 // Do something public static double S1rt'double d) 8 // Do something 9 9 From the previous e*ample" you can notify that the S1rt method is declared as static so that it can be accessed by using the class name directly" no object of the &ath class is re1uired to access the static method. So" here will li%e to some general properties of a static method: t can access only the static fields of the class. t can directly invo%e the methods that are defined as static. Static @iel(s A static field is shared among all the objects of the of the class. So if an object changes this value" then all the objects of this class will get the changed value. class Point 8 public Point') 8 this.* : 6;5 this.y : 6;5 ,onsole.Brite$ine'J0eafult ,onstructor ,alledJ)5 object,ount335 9 public Point'int *" int y) 8 this.* : *5 this.y : y5 ,onsole.Brite$ine'J* : 8G9 " y : 8;9J" *" y)5 object,ount335 9 private int *" y5 public static int object,ount : G5 9 /ow if we create three objects for this class: Point origin; : new Point')5 Point origin< : new Point')5 // objectCount = 1 // objectCount = 2

Point originL : new Point')5 // objectCount = 3 Fere these three objects share the same field so every time the static field object,ount is incremented. Static 8lass A static class is used to hold all the utility methods and fields. A static ,lass has some properties: All the methods and fields inside the class must be declared as static. A static class cannot contain any instance method or data. /o object can be created 'even using the PnewX %eyword) of this class. t can have a default constructor and it is also static. E-a ple $et us consider an e*ample. Point.cs using System5 using System.,ollections.Neneric5 using System.#e*t5 namespace ,onApp,FY,,ons 8 class Point 8 public Point') 8 this.* : 6;5 this.y : 6;5 ,onsole.Brite$ine'J0eafult ,onstructor ,alledJ)5 object,ount335 9 public Point'int *" int y) 8 this.* : *5 this.y : y5 ,onsole.Brite$ine'J* : 8G9 " y : 8;9J" *" y)5 object,ount335 9 public double 0istance#o'Point other) 8 int *0iff : this.* 6 other.*5 int y0iff : this.y 6 other.y5 return &ath.S1rt''*0iff 7 *0iff) 3 'y0iff 7 y0iff))5 9 public static int FnObject,ount')

8 return object,ount5 9 private int *" y5 private static int object,ount : G5 9 9

8onstructorE-a ple.cs using System5 using System.,ollections.Neneric5 using System.#e*t5 namespace ,onApp,FY,,ons 8 class ,onstructorE*ample 8 static void &ain'stringTU args) 8 Point origin : new Point')5 Point bottom.ight : new Point';G<M" ;<SG)5 double distance : origin.0istance#o'bottom.ight)5 ,onsole.Brite$ine'Jdistance : 8G9J"distance)5 ,onsole.Brite$ine'J/o of Objects 8G9J" Point.FnObject,ount'))5 ,onsole..ead$ine')5 9 9 9 n this e*ample" the FnObject,ount') method is called directly with the class name" no object is re1uired here. f you want to access the static method with an object li%e: bottom.ight.FnObject,ount') // do not write this then the compiler will report an error. /ow" ta%e a deeper loo% into the FnObject,ount') static method: public static int FnObject,ount') 8 return object,ount5 9

As it is a static method" it can hold only a static field or static method. "nternal @unction #he internal access specifier hides its member variables and methods from other classes and objects" that is resides in other namespace. #he variable or classes that are declared with internal can be access by any member within application. t is the default access specifiers for a class in ,O programming.
using System; namespace )nternal_.ccess_Specifier / class access / 77 String $ariable declared as internal internal string name; public void print( / Console!"rite#ine("8nMy name is " 9 name ; } } class :rogram / static void Main(string;< args / access ac = ne% access( ; Console!"rite("+nter your name=8t" ; 77 .ccepting value in internal variable ac!name = Console!Read#ine( ; ac!print( ; Console!Read#ine( ; } } }

#he internal %eyword is an access modifier for types and type members. nternal types or members are accessible only within files in the same assembly" as in this e*ample:
public class 3aseClass { 88 9nl! accessible $ithin the sa"e asse"bl! internal static int @ - .; }

#ypes or members that have access modifier protecte( internal can be accessed from the current assembly or from types that are derived from the containing class. For a comparison of internal with the other access modifiers" see Accessibility $evels ',O .eference) and Access &odifiers ',O Programming Nuide). For more information about assemblies" see Assemblies and the Nlobal Assembly ,ache ',O and 2isual @asic). A common use of internal access is in component6based development because it enables a group of components to cooperate in a private manner without being e*posed to the rest of the application code. For e*ample" a framewor% for building graphical user interfaces could provide ,ontrol and Form classes that cooperate by using members with internal access. Since these members are internal" they are not e*posed to code that is using the framewor%.

t is an error to reference a type or a member with internal access outside the assembly within which it was defined. internal members are visible to all code in the assembly they are declared in.'And to other assemblies referenced using the T nternals2isible#oU attribute) private members are visible only to the declaring class. 'including nested classes)For 'hopefully) obvious reasons" an outer 'non6nested) class cannot be declared private. #o answer the 1uestion you forgot to as%" protected members are li%e private members" but are also visible in all classes that inherit the declaring type. '@ut only on an e*pression of at least the type of the current class)
88 Asse"bl!%.cs 88 Co"pile $ith* 8target*librar! internal class 3aseClass { public static int intM - .; }

#he static constructor will be call the first time an object of the type is instantiated or a static method is called. And will only run once #he public constructor is accessible to all other types #he internal constructor is only accessible to types in the same assembly On top of these three thereKs also protected which is only accessible to types derived from the enclosing type and protected internal which is only accessible to types in the same assembly that derives from the enclosing type and private which is only accesible from the type it self or any nested types a static constructor will be called the first time the class is accessed statically. a constructor with an internal access modifier can only be called by items that meet the criteria for internal" which is Jaccessible only within files in the same assemblyJ. a constructor with an public access modifier can be accessed by anything and so on. protected and private constructors operate as you e*pect 6 the constructors are accessible to items that meet the criteria for the access modifier.

Seale( 8lass
Sealed classes are used to restrict the inheritance feature of ob%ect oriented programming. !nce a class is defined as a sealed class, the class cannot be inherited. $n C#, the sealed modifier is used to define a class as sealed. $n (isual )asic .* T the *ot$nheritable"eyword serves the purpose of sealed. $f a class is derived from a sealed class then the compiler throws an error. $f you have ever noticed, structs are sealed. +ou cannot derive a class from a struct. The following class definition defines a sealed class in C#,

88 ealed class sealed class ealedClass {

$n the following code, $ create a sealed class SealedClass and use it from Class-. $f you run this code then it will wor" fine. )ut if you try to derive a class from the SealedClass, you will get an error.
using !ste"; class Class% { static void Main(string+, args) { ealedClass sealedCls - ne$ ealedClass(); int total - sealedCls.Add(;& >); Console.WriteLine("#otal - " ( total.#o tring()); } } 88 ealed class sealed class ealedClass { public int Add(int @& int !) { return @ ( !; } }

MSDN Updated Sealed Methods and Properties You can also use the sealed modifier on a method or a property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent other developers that are using your classes from overriding specific virtual methods and properties. class D { protected virtual void 7() { Console.WriteLine("D.7"); } protected virtual void 7'() { Console.WriteLine("D.7'"); } } class E * D { sealed protected override void 7() { Console.WriteLine("E.7"); } protected override void 7'() { Console.WriteLine("D.7:"); } } class F * E { 88 Atte"pting to override 7 causes co"piler error C .':=. 88 protected override void 7() { Console.WriteLine("C.7"); } 88 9verriding 7' is allo$ed. protected override void 7'() { Console.WriteLine("F.7'"); } } Why Sealed Classes?

We %ust saw how to create and use a sealed class. The main purpose of a sealed class is to ta"e away the inheritance feature from the user so they cannot derive a class from a sealed class. !ne of the best usage of sealed classes is when you have a class with static members. .or example, the /&ens/and /)rushes/ classes of the /System.0rawing/ namespace. The &ens class represents the pens for standard colors. This class has only static members. .or example, /&ens.)lue/ represents a pen with the blue color. Similarly, the /)rushes/ class represents standard brushes. /)rushes.)lue/ represents a brush with blue color. So when you're designing your application, you may "eep in mind that you have sealed classes to seal the user's boundaries. $n the next article of this series, $ will discuss some usage of abstract classes.

,lasses can be declared as sealed. #his is accomplished by putting the sealed %eyword before the %eyword class in the class definition Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as sealed class" this class cannot be inherited. A sealed class cannot be used as a base class. For this reason" it cannot also be an abstract class. Sealed classes are primarily used to prevent derivation. @ecause they can never be used as a base class" some run6time optimi-ations can ma%e calling sealed class members slightly faster.

Partial 8lass
There are several situations when splitting a class definition is desirable: 'hen wor$ing on large pro"ects, spreading a class over separate files enables multiple programmers to wor$ on it at the same time. 'hen wor$ing with automatically generated source, code can be added to the class without having to recreate the source file. *isual +tudio uses this approach when it creates 'indows Forms, 'eb service wrapper code, and so on. #ou can create code that uses these classes without having to modify the file created by *isual +tudio. To split a class definition, use the partial $eyword modifier, as shown here: public partial class ,mployee
{ public void )oWor6() { } } public partial class B"plo!ee { public void 4o#oLunch() { } }

#he partial %eyword indicates that other parts of the class" struct" or interface can be defined in the namespace. All the parts must use the partial %eyword. All the parts must be available at compile time to form the final type. All the parts must have the same accessibility" such as public" pri'ate" and so on. f any part is declared abstract" then the whole type is considered abstract. f any part is declared sealed" then the whole type is considered sealed. f any part declares a base type" then the whole type inherits that class. All the parts that specify a base class must agree" but parts that omit a base class still inherit the

base type. Parts can specify different base interfaces" and the final type implements all the interfaces listed by all the partial declarations. Any class" struct" or interface members declared in a partial definition are available to all the other parts. #he final type is the combination of all the parts at compile time.
The following are merged from all the partial&type definitions: -./ comments interfaces generic&type parameter attributes class attributes members

;here are se'eral rules to follo, ,hen you are ,or+in) ,ith partial class (efinitions9 All partial6type definitions meant to be parts of the same type must be modified with partial. For e*ample" the following class declarations generate an error:
public partial class A { } 88public class A { } 88 Brror& "ust also be "ar6ed partial

#he partial modifier can only appear immediately before the %eywords class" struct" or interface. /ested partial types are allowed in partial6type definitions as illustrated in the following e*ample:

partial class ClassWithNestedClass { partial class NestedClass { } } partial class ClassWithNestedClass { partial class NestedClass { } }

All partial6type definitions meant to be parts of the same type must be defined in the same assembly and the same module '.e*e or .dll file). Partial definitions cannot span multiple modules. #he class name and generic6type parameters must match on all partial6type definitions. Neneric types can be partial. Each partial declaration must use the same parameter names in the same order. #he following %eywords on a partial6type definition are optional" but if present on one partial6type definition" cannot conflict with the %eywords specified on another partial definition for the same type: public private protected internal abstract sealed base class new modifier 'nested parts) generic constraints
(he biggest use o partial classes is make li e easier on code generators ) designers. Partial classes

allow the generator to simpl# emit the code the# need to emit and do not ha&e to deal with user edits to the ile. 5sers are likewise ree to annotate the class with new members b# ha&ing a second partial class. (his pro&ides a &er# clean ramework or separation o concerns. A better wa# to look at it is to see how designers unctioned be ore partial classes. (he %in1orms designer would spit out all o the code inside o a region with strongl# worded comments about not modi #ing the code. /t had to insert all sorts o heuristics to ind the generated code or later processing. 6ow it can simpl# open the designer.cs ile and ha&e a high degree o con idence that it contains onl# code relati&e to the designer.

Advantages of a 0artial 1lass


2ere is a list of some of the advantages of partial classes: ;.#ou can separate 3I design code and business logic code so that it is easy to read and understand. For example, you are developing a web application using *isual +tudio and add a new web form then there are two source files, 4aspx.cs4 and 4aspx.designer.cs4. These two files have the same class with the partial $eyword. The 4.aspx.cs4 class has the business logic code while 4aspx.designer.cs4 has user interface control definition. <.'hen wor$ing with automatically generated source, the code can be added to the class without having to recreate the source file. For example, you are wor$ing with /I56 to +6/ and create a D!./ file. 5ow when you drag and drop a table, it creates a partial class in designer.cs and all table columns have properties in the class. #ou need more columns in this table to bind on the 3I grid but you don(t want to add a new column to the database table so you can create a separate source file for this class that has a new property for that column and it will be a partial class. +o that does affect the mapping between database table and D!./ entity but you can easily get an extra field. It means you can write the code on your own without messing with the system generated code. 7..ore than one developer can simultaneously write the code for the class. 8.#ou can maintain your application better by compacting large classes. +uppose you have a class that has multiple interfaces so you can create multiple source files depending on interface implements. It is easy to understand and maintain an interface implemented on which the source file has a partial class. /et(s see the following code snippet.

Points ;hat Fou Shoul( be 8areful about Partial 8lasses


There are some points that you should be careful about when you are developing a partial class in your application. ;.#ou need to use partial $eyword in each part of partial class. <.The name of each part of partial class should be the same but source file name for each part of partialclass can be different. L.All parts of a partial class should be in the same namespace. M.,ach part of a partial class should be in the same assembly or D//, in other words you can(t create apartial class in source files of a different class library pro"ect. C.,ach part of a partial class has the same accessibility. =.If you inherit a class or interface on a partial class, then it is inherited on all parts of a partial class. Y.If a part of a partial class is sealed, then the entire class will be sealed. S.If a part of partial class is abstract, then the entire class will be an abstract class.

Partial &ethods
Partial methods are a new feature available in C# 3.0 that don't seem to get enough credit. I think there was a lot of confusion early on about what partial methods were and how they were used.

Partial methods are intended to solve a major problem that is not only caused by code-generation tools and also affects those same tools. For instance, you are writing a code-generation tool but want to provide a way for the developers that are using your generated classes to hook in to specific areas of the code. As such, you don't want them editing your generated code since those customizations will be lost the next time the tool runs. On the flip side of this scenario is the developer who needs to write the code that hooks into those specific areas and doesn't want that code being lost the next time the tool runs. Delegates are one solution to this type of problem. In the generated code, you declare a delegate method that you then call at the appropriate areas. If no one has implemented a concrete version of the delegate, the call will not do anything. However, if someone has implemented am instance of that delegate then the call will run the code in that instance. This sounds like a pretty good solution, and, until partial methods it really was the only solution. The drawback is that the code for the delegate is always compiled in to the runtime of your application and add to the runtime overhead of application (granted, that overhead is minimal but it's still there). Partial classes helped with this problem by allowing the code-generation tools to isolate the generated code in a partial class. This allowed the developer to add their own methods to the class without fear that they would be overwritten the next time the tool ran. However, it only helped partially. In order to accomplish our scenario, you still needed to provide a delegate to allow the developer to hook into your process. If we take this a step further and look at partial methods, you will start to see how they work and what the benefit is of using them. The following rules govern how partials methods can be declared and used: 1.Must be declared inside a partial class.

<.Must be declared as a void return type. L.Must be declared with the partial. M.Cannot be marked as extern. C.Can be marked static or unsafe.
6.Can be generic.

Y.Can have ref but not out parameters.


8.Cannot be referenced as a delegate until they are implemented

W.Cannot have access modifiers such as public, private or internal. ;G.Cannot be declared as virtual.
Partial methods are implicitly marked as private. This means they cannot be called from outside the partial class. Now that we have the rules out of the way, let's take a look at an example. This is a completely contrived example, as you typically wouldn't declare both portions of the partial class yourself.

Generics in C#
7enerics are the most power ul eature o !8 . 7enerics allow #ou to de ine t#pe'sa e data structures,

without committing to actual data t#pes. (his results in a signi icant per ormance boost and higher 3ualit# code, because #ou get to reuse data processing algorithms without duplicating t#pe'speci ic code. /n concept, generics are similar to !99 templates, but are drasticall# di erent in implementation and capabilities.
1enerics provide the solution to a limitation in earlier versions of the common language runtime and the C# language in which generali2ation is accomplished by casting types to and from the universal base type !b%ect. )y creating a generic class, you can create a collection that is type-safe at compile-time. The limitations of using non3generic collection classes can be demonstrated by writing a short program that ma"es use of the .rray#ist collection class from the .* T .ramewor" base class library. .rray#ist is a highly convenient collection class that can be used without modification to store any reference or value type. using using using using System; System!Collections; System!Collections!(eneric; System!0e,t;

namespace (enerics / class (eneric#ist / static void Main(string;< args / // The .NET Framework 1.1 way to create a List .rray#ist list = ne% .rray#ist( ; 77 .dd an integer to t-e #ist list!.dd(> ; 77 .dd a string to t-e #ist! 0-is %ill compile? 77 but may cause a Runtime +rror@ list.Add("This will trigger a Runtime Error "!" 77 "e cast to int? but t-is %ill causes an )nvalidCast+,ception 77 %-en encounter a string in t-e #ist! int t # (int!list$1%" t = A; foreac- (int , in list / t 9= ,; } // The .NET Framework &.' way to create a List List(int) list1 # new List(int)(!" 77 No bo,ing? no casting listB!.dd(> ; listB!.dd(B ; 77 Compile5time error= listB!.dd("0-is %ill trigger a Compile5time +rror@" ; 77 (et t-e values from t-e #ist? no casting int t1 # list1$1%" tB = A; foreac- (int , in listB / tB 9= ,; }

} }

Generics allow you to delay the specification of the data type of programming elements in a class or a method" until it is actually used in the program. n other words" generics allow you to write a class or method that can wor% with any data type. Dou write the specifications for the class or the method" with substitute parameters for data types. Bhen the compiler encounters a constructor for the class or a function call for the method" it generates code to handle the specific data type. A simple e*ample would help understanding the concept: @eatures of Generics Esing generics is a techni1ue that enriches your programs in the following ways: t helps you to ma*imi-e code reuse" type safety" and performance. Dou can create generic collection classes. #he ./E# Framewor% class library contains several new generic collection classes in the System.Collections.Generic namespace. Dou may use these generic collection classes instead of the collection classes in the System.Collectionsnamespace. Dou can create your own generic interfaces" classes" methods" events and delegates. Dou may create generic classes constrained to enable access to methods on particular data types. Dou may get information on the types used in a generic data type at run6time by means of reflection.

Introduction to Generic Collections


4ll the way bac" in 5esson 67, you learned about arrays and how they allow you to add and retrieve a collection of ob%ects. 4rrays are good for many tas"s, but C# v7.6 introduced a new feature called generics. 4mong many benefits, one huge benefit is that generics allow us to create collections that allow us to do more than allowed by an array. This lesson will introduce you to generic collections and how they can be used. 8ere are the ob%ectives for this lesson, 9nderstand how generic collections can benefit you 5earn how to create and use a generic 5ist Write code that implements a generic 0ictionary

What Can Generics Do For Me?


Throughout this tutorial, you've learned about types, whether built3in :int, float, char; or custom :Shape, ustomer, !ccount;. $n .* T v-.6 there were collections, such as the !rray"ist for wor"ing with groups of ob%ects. 4n !rray"ist is much li"e an array, except it could automatically grow and offered many convenience methods that arrays don't have. The problem with !rray"ist and all the other .* T v-.6 collections is that they operate on typeob#ect. Since all ob%ects derive from the ob#ect type, you can assign anything to an !rray"ist. The problem with this is that you incur performance overhead converting value type ob%ects to and from the ob#ect type and a single !rray"ist could accidentally hold different types, which would cause hard to find errors at runtime because you wrote code to wor" with one type. 1eneric collections fix these problems. 4 generic collection is strongly typed :type safe;, meaning that you can only put one type of ob%ect into it. This eliminates type mismatches at runtime. 4nother benefit of type safety is that performance is better with value type ob%ects because they don't incur overhead of being converted to and from type ob#ect. With generic collections, you have the best of all worlds because they are strongly typed, li"e arrays, and you have the additional functionality, li"e !rray"ist and other non3generic collections, without the problems. The next section will show you how to use a generic "ist collection.

8reatin) Generic List<T> 8ollections #he pattern for using a generic ist collection is similar to arrays. Dou declare the ist" populate its members" then access the members. FereKs a code e*ample of how to use a ist: $ist(int+ my nts : new $ist(int+')5 my nts.Add';)5 my nts.Add'<)5 my nts.Add'L)5 for 'int i : G5 i ( my nts.,ount5 i33) 8 ,onsole.Brite$ine'J&y nts: 8G9J" my ntsTiU)5 9 #he first thing you should notice is the generic collection ist!int"" which is referred to as $ist of int. f you loo%ed in the documentation for this class" you would find that it is defined as ist!#"" where # could be any type. For e*ample" if you wanted the list to wor% on string or Customer objects" you could define them as ist!string" or ist!Customer" and they would hold only string or Customer objects. n the e*ample above" my$nts holds only type int. Esing the Add method" you can add as many int objects to the collection as you want. #his is different from arrays" which have a fi*ed si-e. #he ist!#" class has many more methods you can use" such as Contains" %emo&e" and more. #here are two parts of the 'or loop that you need to %now about. First" the condition uses the Count property of my$nts. #his is another difference between collections and arrays in that an array uses a ength property for the same thing. /e*t" the way to read from a specific position in the ist!#" collection" my$nts(i) " is the e*act same synta* you use with arrays. #he ne*t time you start to use a single6dimension array" consider using a ist!#" instead. #hat said" be sure to let your solution fit the problem and use the best tool for the job. i.e. itKs common to wor% with byte() in many places in the ./E# Framewor%. "Enu erable an( 4rray2 "Hist an( Hist? Enumerable provides only minimal JiterableJ functionality. Dou can traverse the se1uence" but thatKs about it. #his has disadvantages 66 for e*ample" it is very inefficient to count elements using Enumerable" or to get the nth element 66 but it has advantages too 66 for e*ample" an Enumerable could be an endless se1uence" li%e the se1uence of primes. Array is a fi*ed6si-e collection with random access 'i.e. you can inde* into it). $ist is a variable6si-e collection 'i.e. you can add and remove elements) with random access. $ist is an interface which abstracts list functionality 'count" add" remove" inde*er access) away from the various concrete classes such as $ist" @inding$ist" Observable,ollection" etc. Enumerable is an interface that allows the iteration through a collection of items 'e.g. via the foreach %eyword). An array is a ./E# intrinsic. t holds items of the same type" but it is of a fi*ed si-e. Once you create an array with * elements" it cannot grow or shrin%. $ist defines the interface for a list" and also implements Enumerable. $ist implements the $ist interface5 it is a concrete type of list.

#he difference between ./E# $ists and arrays is that lists can have elements added to them 66 they grow to be big enough to hold all of the re1uired items. #he list stores this internally in an array and" when the array is no longer big enough to hold all of the elements" a new array is created and the items copied across. $ist 4 arrays both implement Enumerable. #hatKs how interfaces wor% 66 classes implement the contract and behave in a similar fashion and can be treated similarly as a result 'you %now that the class implements Enumerable" you donKt need to %now the hows or the whys). suggest you read up on interfaces and so forth.
1Bnu"erable is a general'purpose inter ace that is used b# man# classes, such as Arra!, Listand tring in order to let someone iterate o&er a collection. :asicall#, it4s what dri&es the 0oreachstatement. 1List is t#picall# how #ou e"pose &ariables o t#pe List to end users. (his inter ace permits random access to the underl#ing collection.

"Enu erable Enumerable(#+ represents a series of items that you can iterate over 'using foreach" for e*ample) Enumerable doesnKt have the ,ount method and you canKt access the collection through an inde* 'although if you are using $ /V you can get around this with e*tension methods). Enumerable is a general6purpose interface that is used by many classes" such as Array" $ist and String in order to let someone iterate over a collection. @asically" itKs what drives the foreach statement. As a rule of thumb you should always return the type thatKs highest in the object hierarchy that wor%s for the consumers of this method. n your case Enumerable(#+. "Hist $ist(#+ is a collection that you can add to or remove from. $ist has count method and accessed using inde*. $ist is typically how you e*pose variables of type $ist to end users. #his interface permits random access to the underlying collection. f the consumers of the class need to add elements" access elements by inde*" remove elements you are better off using an $ist(#+. 2ashTable
2ashtable optimi9es loo$ups. It computes a hash of each $ey you add. It then uses this hash code to loo$ up the element very :uic$ly. It is an older .5,T Framewor$ type. It is slower than the generic )ictionar! type. using +ystem.1ollections;
class 2rogra" { static Gashtable 4etGashtable() { // Create and return new #ashtable$ Gashtable hashtable - ne$ Gashtable(); hashtable.Add("Area"& %...); hashtable.Add("2eri"eter"& >>);

hashtable.Add("Mortgage"& >;.); return hashtable; } public { Gashtable hashtable - 4etGashtable(); // %ee if the #ashtable contains this key$ Console.WriteLine(hashtable.Contains?e!("2eri"eter")); // Test the Contains method$ !t works the same way$ Console.WriteLine(hashtable.Contains("Area")); // &et value of Area with inde'er$ int value - (int)hashtable+"Area",; // (rite the value of Area$ Console.WriteLine(value); } } static void Main()

Dictionary A dictionary is used where fast loo$ups are critical. The )ictionar! type provides fast loo$ups with $eys to get values. 'ith it we use $eys and values of any type, including ints and strings. Dictionary re:uires a special syntax form. Dictionary is used when we have many different elements. 'e specify its $ey type and its value type. It provides good performance. class Dict
{ static void Main() { // )'ample "ictionary again )ictionar!Hstring& intI d - ne$ )ictionar!Hstring& intI() { {"Lion"& '}& {"dog"& %}}; // *oop over pairs with foreach 0oreach (?e!Jalue2airHstring& intI pair in d) { Console.WriteLine ("{.}& {%}"&pair.?e!& } 0oreach (var pair in d) { Console.WriteLine("{.}& {%}"& pair.?e!& pair.Jalue); } Console.5ead?e!(); } } pair.Jalue);

Dictionary: It returns error if we try to find a $ey which does not exist. It is faster than a 2ashtable because there is no boxing and unboxing. nly public static members are thread safe. Dictionary is a generic type which means we can use it with any data type.

Hashtable:
It returns null if we try to find a $ey which does not exist.

It is slower than dictionary because it re:uires boxing and unboxing. All the members in a 2ashtable are thread safe, 2ashtable is not a generic type,

Dou use a hashtable 'dictionary) when you want fast loo% up access to an item based on a %ey. f you are using $ist" $ist or Enumerable generally this means that you are looping over data 'well in the case of Enumerable it definitely means that)" and a hashtable isnKt going to net you anything. /ow if you were loo%ing up a value in one list and using that to access data in another list" that would a little different. For e*ample: ;.Find position in list of tem foo. <.Position in list for foo corresponds to position in another list which contains FooI2alue. L.Access position in seconds list to get FooI2alue.

"nheritance
nheritance means parent6child relationship.@y using nheritance methodology we can create a new class by using e*isting class code 'i.e. reuse e*isting methods" properties etc). t also referred to as reusability of the code so by using nheritance we can reuse the code again and again. Bhat Be ,all n nheritance main e*isting class is called as generali-ed class" base class" super class and parent class and the new class created from e*isting class is called as speciali-ed class" sub class" child class and derived class. Be normally tal% in terms of base class and derived class. Synta* of nheritance ; class Parent,lass8 < L ...parent class code M C 9 = Y class ,hild,lass : Parent,lass8 S ...child class code W 9 Special ,haracter J:J in nheritance nheritance uses special character called J:J colon to ma%e a relationship between parent and child as you can see in above synta* of code. Bhen to mplement nteritance Bhen we create a new class and we want to reuse some of the methods or properties from e*isting class then that is an ideal time to implement inheritance. Advantage of nteritance .eusability of the code.

#ypes of inheritance in cO #here are C types of inheritance as shown below. ;.Single nheritance <.&ultilevel nheritance L.&ultiple nheritance M.Fierarchical nheritance C.Fybrid nheritance Single nheritance Single nheritance means when a single base is been implemented to single derived class is called as Single nheritance.&eans we have only one parent class and one child class. E*ample of Single nheritance G; class ,ompany8 G< GL public 'oi( ,ompany/ame')8 GM GC ,onsole.Brite$ine'J/ame of the ,ompanyJ)5 G= GY 9 GS GW public 'oi( ,ompanyAddress')8 ;G ;; ,onsole.Brite$ine'JAddress of the ,ompanyJ)5 ;< ;L 9 ;M ;C 9 ;= ;Y class Employee : ,ompany 8 ;S ;W public 'oi( /ameofEmployee')8 <G <; ,onsole.Brite$ine'J/ame of the EmployeeJ)5 << <L 9 <M <C public 'oi( Salary')8 <= <Y ,onsole.Brite$ine'JSalary of the EmployeeJ)5 <S <W 9 LG L; 9 As you can see from the above code that we have implemented single inheritance.

&ultilevel nheritance Bhen a derived class is created from another derived class or let me put it in this way that a class is created by using another derived class and this type of implementation is called as multilevel nheritance

E*ample of &ultilevel nheritance ; class FeadOffice8 < L public 'oi( FeadOfficeAddress')8 M C ,onsole.Brite$ine'JFead Office AddressJ)5 = Y 9 S 9 /ow letKs assume that class JFeadOfficeJ is our Parent class or @ase class. /ow in my ne*t step i will create one derived class. ; class @ranchOffice : FeadOffice8 < L public 'oi( @ranchOfficeAddress')8 M C ,onsole.Brite$ine'J@ranch Office AddressJ)5 = Y 9 S W 9 So as you can see that i have created a derived class J@ranchOfficeJ by implementing the class JFeadOfficeJ to it. t means now we have one parent class and one derived class. n the ne*t step i will create another derived class by implementing our e*isting derived class J@ranchOfficeJ to achieve multilevel nheritance. G; class Employee : @ranchOffice 8 G< GL public 'oi( /ameofEmployee')8 GM GC ,onsole.Brite$ine'J/ame of the EmployeeJ)5 G= GY 9 GS GW public 'oi( Salary')8 ;G ;; ,onsole.Brite$ine'JSalary of the EmployeeJ)5 ;< ;L 9 ;M ;C 9 From the above souce code you can see that we have achieved multilevel nheritance by

implementing one derived class to another derived class. /ow the class JEmployeeJ will have the access of all the properties and methods of class J@ranchOfficeJ and class JFeadOfficeJ. &ultiple nheritance 0ue to the comple*ity of a code multiple inheritance is not been supported in ,O or in 0O#./E# but 0O#./E# or ,O supports multiple interfaces. Fierarchical nheritance Bhen more than one derived classes are implemented from a same parent class or base class then that type of implentation is %nown as hierarchical inheritance. n short it means single base class having more than one derived classes. G; class FeadOffice8 G< GL public 'oi( FeadOfficeAddress')8 GM GC ,onsole.Brite$ine'JFead Office AddressJ)5 G= GY 9 GS 9 GW ;G ;; class @ranchOffice; : FeadOffice8 ;< ;L public 'oi( @ranchOfficeAddress')8 ;M ;C ,onsole.Brite$ine'J@ranch Office AddressJ)5 ;= ;Y 9 ;S ;W 9 <G <; class @ranchOffice< : FeadOffice8 << <L public 'oi( @ranchOfficeAddress')8 <M <C ,onsole.Brite$ine'J@ranch Office AddressJ)5 <= <Y 9 <S <W 9 As you can see from above the code that we have one base class JFeadOfficeJ and two derived classes J@ranchOffice;J and J@ranchOffice<J which are implemented from same base class i.e. JFeadOfficeJ. Fybrid nheritance #his is a special type of inheritance and can be achieved from any combination of single" hierarchical and multi level inheritance %nown as hybrid inheritance.

n the below code e*ample i have combined hierarchical inheritance and multi level inheritance together. G; !!#his part of code is related to hierarchical inheritance G< class FeadOffice8 GL GM public 'oi( FeadOfficeAddress')8 GC G= ,onsole.Brite$ine'JFead Office AddressJ)5 GY GS 9 GW 9 ;G ;; ;< class @ranchOffice; : FeadOffice8 ;L ;M public 'oi( @ranchOfficeAddress')8 ;C ;= ,onsole.Brite$ine'J@ranch Office AddressJ)5 ;Y ;S 9 ;W <G 9 <; << class @ranchOffice< : FeadOffice8 <L <M public 'oi( @ranchOfficeAddress')8 <C <= ,onsole.Brite$ine'J@ranch Office AddressJ)5 <Y <S 9 <W LG 9 G; !!!!#his part of code is related to combination of hierarchical inheritance and multi level inheritance

G< GL class Employee : @ranchOffice< 8 GM GC public 'oi( /ameofEmployee')8 G= GY ,onsole.Brite$ine'J/ame of the EmployeeJ)5 GS GW 9 ;G ;; public 'oi( Salary')8 ;< ;L ,onsole.Brite$ine'JSalary of the EmployeeJ)5 ;M ;C 9 ;= ;Y 9

So that you have understood the inheritance and their C types. /ow letKs a simple e*ample of inheritance using csharp. E*ample of nheritance using ,O G; public class ,ar8 G< pri'ate strin) rearviewmirror5 GL pri'ate strin) gear5 GM pri'ate strin) clutch5 GC pri'ate strin) steering5 G= GY public strin) .ear2iew&irror GS 8 GW )et 8 return rearviewmirror5 9 ;G set 8 rearviewmirror : value5 9 ;; 9 ;< ;L public strin) Near ;M 8 ;C )et 8 return gear5 9 ;= set 8 gear : value5 9 ;Y 9 ;S ;W public strin) ,lutch <G 8 <; )et 8 return clutch5 9 << set 8 clutch : value5 9 <L 9 <M <C public strin) Steering <= 8 <Y )et 8 return steering5 9 <S set 8 steering : value5 9 <W 9 LG L; public 'irtual 'oi( ,arPrice') L< 8 LL ,onsole.Brite$ine'J,ar Pri-e is : GJ)5 LM 9 LC L= public 'irtual 'oi( /ameof,ar') LY 8 LS ,onsole.Brite$ine'J,ompany /ame of this ,ar is 66 J)5 LW 9 MG M; M< 9 Above i have created a simple class J,arJ with some methods and some properties. /ow ne*t step i will create two classes JSentro,arJ and J@,B,arJ and implement it with a single base class J,arJ 0erived ,lass ; implemented with base class ,ar

G; public class Sentro,ar:,ar G< 8 GL GM public o'erri(e 'oi( ,arPrice') GC 8 G= ,onsole.Brite$ine'J,ar Pri-e is : <.C$ /.J)5 GY 9 GS public o'erri(e 'oi( /ameof,ar') GW 8 ;G ,onsole.Brite$ine'J,ompany /ame of this ,ar is SentroJ)5 ;; 9 ;< 9 0erived ,lass < implemented with base class ,ar G; public class @,B,ar : ,ar G< 8 GL GM public o'erri(e 'oi( ,arPrice') GC 8 G= ,onsole.Brite$ine'J,ar Pri-e is : M.C$ /.J)5 GY 9 GS public o'erri(e 'oi( /ameof,ar') GW 8 ;G ,onsole.Brite$ine'J,ompany /ame of this ,ar is @,B J)5 ;; 9 ;< 9

As you see that we have two derived classes implemented from same base class. #his type of implementation can also be called as Fierarchical nheritance. Output by Esing ,onsole Application G; class Program G< 8 GL static 'oi( &ain'strin)TU args) GM 8 GC G= ,ar obj : ne, Sentro,ar')5 GY obj.,arPrice')5 GS obj./ameof,ar')5 GW ;G ,ar obj : ne, @,B,ar')5 ;; obj.,arPrice')5 ;< obj./ameof,ar')5 ;L 9 ;M 9 !!Output ,ar Pri-e is : <.C$ /. ,ompany /ame of this ,ar is Sentro ,ar Pri-e is : M.C$ /. ,ompany /ame of this ,ar is @,B.
What are the main components of .N ! Frame"or#? .* T .ramewor" provides enormous advantages to software developers in comparison to the advantages provided by other platforms. Microsoft has united various modern as well as existing technologies of software development in .* T .ramewor". These technologies are used by developers to develop highly efficient applications for modern as well as future business needs. The following are the "ey components of .* T .ramewor", .* T .ramewor" Class 5ibrary Common 5anguage <untime 0ynamic 5anguage <untimes :05<; 4pplication 0omains <untime 8ost Common Type System Metadata and Self30escribing Components Cross35anguage $nteroperability .* T .ramewor" Security &rofiling Side3by3Side xecution

$ist the ne" features added in .N ! Frame"or# %.&. The following are the new features of .* T .ramewor" =.6, $mproved 4pplication Compatibility and 0eployment Support 0ynamic 5anguage <untime Managed xtensibility .ramewor" &arallel &rogramming framewor" $mproved Security Model *etwor"ing $mprovements $mproved Core 4S&.* T Services

$mprovements in W&. = $mproved ntity .ramewor" : .; $ntegration between WC. and W.

What is an I$? $ntermediate 5anguage is also "nown as MS$5 :Microsoft $ntermediate 5anguage; or C$5 :Common $ntermediate 5anguage;. 4ll .* T source code is compiled to $5. $5 is then converted to machine code at the point where the software is installed, or at run3time by a >ust3$n3Time :>$T; compiler. What is Manifest? 4ssembly metadata is stored in Manifest. Manifest contains all the metadata needed to do the following things (ersion of assembly. Security identity. Scope of the assembly. <esolve references to resources and classes.

The assembly manifest can be stored in a & file either :an .exe or; .dll with Microsoft intermediate language :MS$5 code with Microsoft intermediate language :MS$5; code or in a stand3alone & file, that contains only assembly manifest information. What are code contracts? Code contracts help you to express the code assumptions and statements stating the behavior of your code in a language3neutral way. The contracts are included in the form of pre3conditions, post3conditions and ob%ect3invariants. The contracts help you to improve3testing by enabling run3time chec"ing, static contract verification, and documentation generation. The System!*iagnostics!Contracts namespace contains static classes that are used to express contracts in your code. Name the classes that are introduced in the *ystem.Numerics namespace. The following two new classes are introduced in the System!Numerics namespace,

&ig)nteger 3 <efers to a non3primitive integral type, which is used to hold a value of any si2e. Comple, 3 <epresents complex numbers and enables different arithmetic operations with
the imaginary part, is a complex number. $t has no lower and upper limit, ma"ing it possible for you to perform arithmetic calculations with very large numbers, even with the numbers which cannot hold by double or long. complex numbers. 4 number represented in the form a 9 bi, where a is the real part, and b is

What is Common !ype System 'C!S(? CTS is the component of C5< through which .* T .ramewor" provides support for multiple languages because it contains a type system that is common across all the languages. Two CTS3compliant languages do not re#uire type conversion when calling the code written in one language from within the code written in another language. CTS provide a base set of data types for all the languages supported by.* T .ramewor". This means that the si2e of integer and long variables is same across all .* T3 compliant programming languages. 8owever, each language uses aliases for the base data types provided by CTS. .or example, CTS uses the data type system. int?7 to represent a = byte integer value@ however, (isual )asic uses the alias integer for the same@ whereas, C# uses the alias int. This is done for the sa"e of clarity and simplicity.

Which method do you use to enforce )ar*a)e collection in .N !? The System!(C!Collect( method.

State the differences *et"een the +is,ose(! and Finali-e(!. C5< uses the 0ispose and .inali2e methods to perform garbage collection of run3time ob%ects of .* T applications. The CinaliDe method is called automatically by the runtime. C5< has a garbage collector :1C;, which periodically chec"s for ob%ects in heap that are no longer referenced by any ob%ect or program. $t calls the .inali2e method to free the memory used by such ob%ects. The *ispose method is called by the programmer.*ispose is another method to release the memory used by an ob%ect. The 0ispose method needs to be explicitly called in code to dereference an ob%ect from the heap. The *ispose method can be invo"ed only by the classes that implement the )*isposable interface. What is code access security 'C+S(? Code access security :C4S; is part of the .* T security model that prevents unauthori2ed access of resources and operations, and restricts the code to perform particular tas"s.

Differentiate *et"een mana)ed and unmana)ed code? Managed code is the code that is executed directly by the C5< instead of the operating system. The code compiler first compiles the managed code to intermediate language :$5; code, also called as MS$5 code. This code doesn't depend on machine configurations and can be executed on different machines. 9nmanaged code is the code that is executed directly by the operating system outside the C5< environment. $t is directly compiled to native machine code which depends on the machine configuration. $n the managed code, since the execution of the code is governed by C5<, the runtime provides different services, such as garbage collection, type chec"ing, exception handling, and security support. These services help provide uniformity in platform and language3independent behavior of managed code applications. $n the unmanaged code, the allocation of memory, type safety, and security is re#uired to be ta"en care of by the developer. $f the unmanaged code is not properly handled, it may result in memory lea". xamples of unmanaged code are 4ctiveA components and Win?7 4&$s that execute beyond the scope of native C5<. What are tuples? Tuple is a fixed3si2e collection that can have elements of either same or different data types. Similar to arrays, a user must have to specify the si2e of a tuple at the time of declaration. Tuples are allowed to hold up from - to B elements and if there are more than B elements, then the Bth element can be defined as another tuple. Tuples can be specified as parameter or return type of a method. ,o" can you turn-on and turn-off C+S? +!9 can use the Code 4ccess Security Tool :Caspol.exe; to turn security on and off. To turn off security, type the following command at the command prompt,

caspol 5security off


To turn on security, type the following command at the command prompt,

caspol 5security on
$n the .* T .ramewor" =.6, for using Caspol.exe, you first need to set the E#egacyCas:olicy6 element totrue. What is )ar*a)e collection? earlier .ersions. -plain the difference *et"een )ar*a)e collections in .N ! %.& and

1arbage collection prevents memory lea"s during execution of programs. 1arbage collector is a low3 priority process that manages the allocation and deallocation of memory for your application. $t chec"s for the unreferenced variables and ob%ects. $f 1C finds any ob%ect that is no longer used by the application, it frees up the memory from that ob%ect.

1C has changed a bit with the introduction of .* T =.6. $n .* T =.6, the (C!Collect( the following overloaded methods, GC.Collect(int) GC.Collect(int, GCCollectionMode)

method contains

4nother new feature introduced in .* T is to notify you when the (C!Collect(

method is invo"ed and

completed successfully by using different methods. The .* T =.6 supports a new bac"ground garbage collection that replaces the concurrent garbage collection used in earlier versions. This concurrent 1C allocates memory while running and uses current segment :which is -C M) on a wor"station; for that. 4fter that, all threads are suspended. $n case of bac"ground 1C, a separate ephemeral 1C 3 gen6 and gen- can be started, while the full 1C 3 gen6, -, and 7 3 is already running. ,o" does C+S "or#s? There are two "ey concepts of C4S security policy3 code groups and permissions. 4 code group contains assemblies in it in a manner that each .* T assembly is related to a particular code group and some permissions are granted to each code group. .or example, using the default security policy, a control downloaded from a Web site belongs to the Done, $nternet code group, which adheres to the permissions defined by the named permission set. :*ormally, the named permission set represents a very restrictive range of permissions.; 4ssembly execution involves the following steps, -. vidences are gathered about assembly. 7. 0epending on the gathered evidences, the assembly is assigned to a code group. ?. Security rights are allocated to the assembly, depending on the code group. =. 4ssembly runs as per the rights assigned to it. E. What is Difference *et"een NameSpace and +ssem*ly? .ollowing are the differences between namespace and assembly, 4ssembly is physical grouping of logical units, *amespace, logically groups classes. *amespace can span multiple assembly.

Mention the e-ecution process for mana)ed code. 4 piece of managed code is executed as follows, Choosing a language compiler Compiling the code to MS$5 Compiling MS$5 to native code xecuting the code.

,o" can you instantiate a tuple? The following are two ways to instantiate a tuple,

9sing the ne% operator. .or example, Tuple<String, int> t = new Tuple<String, int> ("Hellow", 2);

9sing the Create factory method available in the Tuple class. .or example,

Tuple<int, int, int> t = Tuple.Create<int, int, int> (2, 4, 5); What is Microsoft Intermediate $an)ua)e 'MSI$(? The .* T .ramewor" is shipped with compilers of all .* T programming languages to develop programs. There are separate compilers for the (isual )asic, C#, and (isual CFF programming languages in .* T .ramewor". ach .* T compiler produces an intermediate code after compiling the source code. The intermediate code is common for all languages and is understandable only to .* T environment. This intermediate code is "nown as MS$5. What is la/y initiali/ation? 5a2y initiali2ation is a process by which an ob%ect is not initiali2ed until it is first called in your code. The .* T =.6 introduces a new wrapper class, System!#aDyE06, for executing the la2y initiali2ation in your application. 5a2y initiali2ation helps you to reduce the wastage of resources and memory re#uirements to improve performance. $t also supports thread3safety. ,o" many types of )enerations are there in a )ar*a)e collector? Memory management in the C5< is divided into three generations that are build up by grouping memory segments. 1enerations enhance the garbage collection performance. The following are the three types of generations found in a garbage collector, 1eneration 6 3 When an ob%ect is initiali2ed, it is said to be in generation 6. 1eneration - 3 The ob%ects that are under garbage collection process are considered to be in generation -. 1eneration 7 3 Whenever new ob%ects are created and added to the memory, they are added to generation 6 and the old ob%ects in generation - are considered to be in generation 7.

What is Common $an)ua)e Specification 'C$S(? C5S is a set of basic rules, which must be followed by each .* T language to be a .* T3 compliant language. $t enables interoperability between two .* T3compliant languages. C5S is a subset of CTS@ therefore, the languages supported by C5S can use each other's class libraries similar to their own. 4pplication programming interfaces :4&$s;, which are designed by following the rules defined in C5S can be used by all .* T3compliant languages.

What is the role of the 0I! compiler in .N ! Frame"or#? The >$T compiler is an important element of C5<, which loads MS$5 on target machines for execution. The MS$5 is stored in .* T assemblies after the developer has compiled the code written in any .* T3 compliant programming language, such as (isual )asic and C#. >$T compiler translates the MS$5 code of an assembly and uses the C&9 architecture of the target machine to execute a .* T application. $t also stores the resulting native code so that it is accessible for subse#uent calls. $f a code executing on a target machine calls a non3native method, the >$T compiler converts the MS$5 of that method into native code. >$T compiler also enforces type3safety in runtime environment of .* T .ramewor". $t chec"s for the values that are passed to parameters of any method. .or example, the >$T compiler detects any event, if a user tries to assign a ?73bit value to a parameter that can only accept B3bit value.

What is difference *et"een *ystem.*tring and *ystem.*tring.uilder classes?

String and String&uilder classes are used to store string values but the difference in them is that
String is immutable :read only; by nature, because a value once assigned to a String ob%ect cannot be changed after its creation. When the value in the String ob%ect is modified, a new ob%ect is created, in memory, with a new value assigned to the String ob%ect. !n the other hand, the String&uilder class

is mutable, as it occupies the same space even if you change the value. The String&uilder class is more efficient where you have to perform a large amount of string manipulation.

Descri*e the roles of C$1 in .N ! Frame"or#. C5< provides an environment to execute .* T applications on target machines. C5< is also a common runtime environment for all .* T code irrespective of their programming language, as the compilers of respective language in .* T .ramewor" convert every source code into a common language "nown as MS$5 or $5 :$ntermediate 5anguage;. C5< also provides various services to execute processes, such as memory management service and security services. C5< performs various tas"s to manage the execution process of .* T applications. The responsibilities of C5< are listed as follows, 4utomatic memory management 1arbage Collection Code 4ccess Security Code verification >$T compilation of .* T code

What is the difference *et"een int and int23. There is no difference between int and int>F. System!)nt>F is a .* T Class and int is an alias name forSystem!)nt>F.

4SP.:E;
Concept of Postback in ASP !"#$ A postbac$ is a re:uest sent from a client to server from the same page user is already wor$ing with. A+0.5,T was introduced with a mechanism to post an 2TT0 0 +T re:uest bac$ to the same page. It(s basically posting a complete page bac$ to server <i.e. sending all of its data= on same page. +o, the whole page is refreshed. Another concept related to this approach is 41allbac$4 that is also as$ed sometimes during a technical interview :uestion. 1lic$ here to understand 0ostbac$ *s 1allbac$ in A+0.5,T. ASP !"# Pa%e life Cycle

Pre"nit9
Dou can:

,hec% for the sPost@ac% property to determine whether this is the first time the page is being processed.
,reate or recreate dynamic controls. Set master page dynamically. Set the #heme property dynamically. .ead or set profile property values. f .e1uest is postbac%:

#he values of the controls have not yet been restored from view state. f you set control property at this stage" its value might be overwritten in the ne*t event.

"nit9 n the nit event of the individual controls occurs first" later the nit event of the Page ta%es place.
#his event is used to initiali-e control properties.

"nit8o plete9
#rac%ing of the 2iewState is turned on in this event. Any changes made to the 2iewState in this event are persisted even after the ne*t postbac%.

PreHoa(9
#his event processes the postbac% data that is included with the re1uest.

Hoa(9 n this event the Page object calls the On$oad method on the Page object itself" later the On$oad method of the
controls is called. #hus $oad event of the individual controls occurs after the $oad event of the page.

8ontrolE'ents9 #his event is used to handle specific control events such as a @utton controlAs ,lic% event or
a #e*t@o*controlAs #e*t,hanged event. n case of postbac%:

f the page contains validator controls" the Page. s2alid property and the validation of the controls ta%es place
before the firing of individual control events.

Hoa(8o plete9
#his event occurs after the event handling stage. #his event is used for tas%s such as loading all other controls on the page.

PreEen(er9 n this event the Pre.ender event of the page is called first and later for the child control.
Esage:

#his method is used to ma%e final changes to the controls on the page li%e assigning the 0ataSource d and
calling the 0ata@ind method.

PreEen(er8o plete9 #his event is raised after each controlKs Pre.ender property is completed. Sa'eState8o plete9
#his is raised after the control state and view state have been saved for the page and for all controls.

Een(er8o plete9
#he page object calls this method on each control which is present on the page. #his method writes the controlAs mar%up to send it to the browser.

<nloa(9 #his event is raised for each control and then for the Page object.
Esage: Ese this event in controls for final cleanup wor%" such as closing open database connections" closing open files" etc.

+ection GttpModule

,vent 3egin5eKuest

Description This event signals a new re:uest; it is guaranteed to

+ection

,vent

Description be raised on each re:uest. This event signals that A+0.5,T runtime is ready to authenticate the user. Any authentication code can be in"ected here. This event signals that A+0.5,T runtime is ready to authori9e the user. Any authori9ation code can be in"ected here. In A+0.5,T, we normally use outputcache directive to do caching. In this event, A+0.5,T runtime determines if the page can be served from the cache rather than loading the patch from scratch. Any caching specific activity can be in"ected here. This event signals that A+0.5,T runtime is ready to ac:uire session variables. Any processing you would li$e to do on session variables. This event is raised "ust prior to handling control to the GttpGandler. !efore you want the control to be handed over to the handler any pre&processing you would li$e to do.

GttpModule

Authenticate5eKuest

GttpModule

AuthoriAe5eKuest

GttpModule

5esolve5eKuestCache

GttpModule

AcKuire5eKuest tate

GttpModule

2re5eKuestGandlerB@ecute

GttpGandler 2rocess5eKuest

Gttphandler logic is executed. In this section, we will write logic which needs to be executed as per page extensions.
This event happens in the A+0.5,T page and can be used for: 1reating controls dynamically, in case you have controls to be created on runtime. Any setting initiali9ation. .aster pages and the settings. In this section, we do not have access to viewstate, postedvalues and neither the controls are initiali9ed. In this section, the A+0.5,T controls are fully loaded and you write 3I manipulation logic or any other logic over here. If you have valuators on your page, you would li$e to chec$ the same here. It>s now time to send the output to the browser. If you would li$e to ma$e some changes to the final 2T./ which is going out to the browser, you can enter your 2T./ logic here. 0age ob"ect is unloaded from the memory. Any logic you would li$e to in"ect after the handlers are executed. If you would li$e to save update some state variables li$e session variables. !efore you end, if you want to update your cache. This is the last stage before your output is sent to the client browser.

2age

1nit

2age 2age

Load Jalidate

5ender 2age GttpModule GttpModule GttpModule GttpModule Lnload 2ost5eKuestGandlerB@ecute 5eleasereKuest tate Lpdate5eKuestCache Bnd5eKuest

Sta)e Page re1uest

Start

nitiali-ation

$oad Postbac% event handling

.endering

Enload

%escription #he page re1uest occurs before the page life cycle begins. Bhen the page is re1uested by a user" ASP./E# determines whether the page needs to be parsed and compiled 'therefore beginning the life of a page)" or whether a cached version of the page can be sent in response without running the page. n the start stage" page properties such as .e1uest and .esponse are set. At this stage" the page also determines whether the re1uest is a postbac% or a new re1uest and sets the sPost@ac% property. #he page also sets the E ,ulture property. 0uring page initiali-ation" controls on the page are available and each controlKs Eni1ue 0 property is set. A master page and themes are also applied to the page if applicable. f the current re1uest is a postbac%" the postbac% data has not yet been loaded and control property values have not been restored to the values from view state. 0uring load" if the current re1uest is a postbac%" control properties are loaded with information recovered from view state and control state. f the re1uest is a postbac%" control event handlers are called. After that" the 2alidate method of all validator controls is called" which sets the s2alidproperty of individual validator controls and of the page. '#here is an e*ception to this se1uence: the handler for the event that caused validation is called after validation.) @efore rendering" view state is saved for the page and all controls. 0uring the rendering stage" the page calls the .ender method for each control" providing a te*t writer that writes its output to the OutputStream object of the pageKs .esponse property. #he Enload event is raised after the page has been fully rendered" sent to the client" and is ready to be discarded. At this point" page properties such as.esponse and .e1uest are unloaded and cleanup is performed.

State

ana)e ent?

Beb is Stateless. t means a new instance of the web page class is re6created each time the page is posted to the server. As we all %now F##P is a stateless protocol" its canKt holds the client information on page. As for e*ample " if we enter a te*t and client on submit button" te*t does not appear after post bac% " only because of page is recreated on its round trip. As given in above pages" page is recreated before its comes to clients and happened for each and every re1uest. So it is a big issue to maintain the state of the page and information for a web application. #hat is the reason to start concept of State &anagement. #o overcome this problem ASP./E# <.G Provides some features li%e 2iew State" ,oo%ies" Session" Application objects etc. to manage the state of page. #here are some few selection criteria to selected proper way to maintain the state" as there are many way to do that. #hose criteria are: Fow much information do you need to storeQ 0oes the client accept persistent or in6memory coo%iesQ 0o you want to store the information on the client or on the serverQ s the information sensitiveQ Bhat performance and bandwidth criteria do you have for your applicationQ

Bhat are the capabilities of the browsers and devices that you are targetingQ 0o you need to store information per userQ Fow long do you need to store the informationQ 0o you have a Beb farm 'multiple servers)" a Beb garden 'multiple processes on one machine)" or a single process that serves the applicationQ So" when ever you start to thin% about state management" you should thin% about above criteria. based on that you can choose the best approaches for manages state for your web application. 0ifferent types of state managementQ #here are two different types of state management: ;.,lient Side State &anagement 2iew State Fidden Field ,oo%ies ,ontrol State <.Server Side State &anagement Session Application Object ,aching 0atabase ,lient Side state management does not use any server resource " it store information using client side option. Server Side state management use server side resource for store data. Selection of client side and server side state management should be based on your re1uirements and the selection criteria that are already given. What is 'ie, state? 2iew State is one of the most important and useful client side state management mechanism. t can store the page value at the time of post bac% 'Sending and .eceiving information from Server) of your page. ASP./E# pages provide the 2iewState property as a built6in structure for automatically storing values between multiple re1uests for the same page. E*ample: f you want to add one variable in 2iew State" ,ollapse Z ,opy ,ode 2iewStateTJ2arJU:,ount5 For .etrieving information from 2iew State ,ollapse Z ,opy ,ode string #est:2iewStateTJ#est2alJU5 Sometimes you may need to typecast 2iewState 2alue to retreive. As give an E*ample to strore and retreive object in view state in the last of this article. 4('anta)es of 'ie, state? #his are the main advantage of using 2iew State: Easy to implement /o server resources are re1uired Enhanced security features "li%e it can be encoded and compressed. %isa('anta)es of 'ie, state? #his are the main disadvantages of using 2iew State: t can be performance overhead if we are going to store larger amount of data " because it is associated with page only. ts stored in a hidden filed in hashed format 'which have discussed later) still it can be easily

trapped. t does not have any support on mobile devices. When ,e shoul( use 'ie, state? already describe the criteria of selecting State management. A few point you should remember when you select view state for maintain your page state. Si-e of data should be small " because data are bind with page controls " so for larger amount of data it can be cause of performance overhead. #ry to avoid storing secure data in view state Bhen we should avoid view stateQ Dou wonKt need view state for a control for following cases" #he control never change #he control is repopulated on every postbac% #he control is an input control and it changes only of user actions. Bhere is view state storedQ 2iew State stored the value of page controls as a string which is hashed and encoded in some hashing and encoding technology. t only contain information about page and its controls. ts does not have any interaction with server. t stays along with the page in the ,lient @rowser. 2iew State use Fidden field to store its information in a encoding format. Suppose you have written a simple code " to store a value of control: ,ollapse Z ,opy ,ode 2iewStateTJ2alueJU : &y,ontrol.#e*t5 /ow" .un you application" n @rowser" .igh,lic% + 2iew Source " Dou will get the following section of code Fig : 2iew state stored in hidden field /ow " loo% at the value. loo%s li%es a encrypted string" #his is @ase=M Encoded string" this is not a encoded string. So it can easily be decoded. @ase=M ma%es a string suitable for F##P transfer plus it ma%es it a little hard to read . .ead &ore about @ase=M Encoding . Any body can decode that string and read the original value. so be careful about that. #here is a security lac% of view state. Fow to store object in view stateQ Be can store an object easily as we can store string or integer type variable. @ut what we need Q we need to convert it into stream of byte. because as already said " view state store information in hidden filed in the page. So we need to use Seriali-ation. f object which we are trying to store in view state "are not seriali-able " then we will get a error message . Rust ta%e as e*ample" ,ollapse Z ,opy ,ode //Create a sim*le class and ma+e it as Seriali,able TSeriali-ableU public class student 8 public int .oll5 public string /ame5 public void AddStudent'int int.oll"int str/ame) 8 this..oll:int.oll5 this./ame:str/ame5 9

9 /ow we will try to store object of JStudentJ ,lass in a view state. ,ollapse Z ,opy ,ode //Store Student Class in -iew State student IobjStudent : new student')5 IobjStudent.AddStudent'<" JAbhijitJ)5 2iewStateTJStudentObjectJU : IobjStudent5 //%etrie&e Student in'ormation &iew state student IobjStudent5 IobjStudent : 'student)2iewStateTJStudentObjectJU5 Fow to trace your view state informationQ f you want to trace your view state information" by just enable J#raceJ option of Page 0irective /ow .un your web application" Dou can view the details of 2iew State Si-e along with control 0 in ,ontrol #reeSection. 0onKt worry about J.ender Si-e @yteJ " this only the si-e of rendered control. Fig : View State Details Enabling and 0isabling 2iew State Dou can enable and disable 2iew state for a single control as well as at page level also. #o turnoff view state for a single control " set Enable2iewState Property of that control to false. e.g.: ,ollapse Z ,opy ,ode #e*t@o*;.Enable2iewState :false5 #o turnoff the view state of entire page" we need to set Enable2iewState to false of Page 0irective as shown bellow. Even you disable view state for the entire page " you will see the hidden view state tag with a small amount of information" ASP./E# always store the controls hierarchy for the page at minimum " even if view state is disabled. For enabling the same" you have to use the same property just set them as #rue as for e*ample" for a single control we can enabled view state in following way" ,ollapse Z ,opy ,ode #e*t@o*;.Enable2iewState :true5 and for a page level" Fow to ma%e view state secureQ As already discuss 2iew state information is stored in a hidden filed in a form of @ase=M Encoding String" and it loo%s li%e: Fig : View state store in !i en "iel &any of ASP./E# Programmers assume that this is an Encrypted format" but am saying it again" that this is not a encrypted string. t can be brea% easily. #o ma%e your view state secure" #here are two option for that" First" you can ma%e sure that the view state information is tamper6proof by using Jhash codeJ. Dou

can do this by adding JEnable2iewState&A,:trueJ with your page directive. &A, Stands for J&essage Authentication ,odeJ A hash code " is a cryptographically strong chec%sum" which is calculated by ASP./E# and its added with the view state content and stored in hidden filed. At the time of ne*t post bac%" the chec%sum data again verified " if there are some mismatch" Post bac% will be rejected. we can set this property to web.config file also. Second option is to set 2iewStateEncryption&ode:JAlwaysJ with your page directives" which will encrypt the view state data. Dou can add this in following way t 2iewStateEncryption&ode has three different options to set: Always Auto /ever Always" mean encrypt the view state always" /ever means" /ever encrypt the view state data and Auto Says " encrypt if any control re1uest specially for encryption. For auto " control must callPage..egister.e1uires2iewStateEncryption') method for re1uest encryption. we can set the Setting for JEnable2iewState&A,J and 2iewStateEncryption&odeJ in web.config also. /ote : #ry to avoid 2iew State Encryption if not necessary " because it cause the performance issue.
What is +uto4ost5ac#? $f you want a control to postbac" automatically when an event is raised, you need to set the .uto:ost&ac'property of the control to 0rue. What is the function of the 6ie"State property? The 4S&.* T =.6 introduced a new property called $ie%StateMode for the Control class. *ow you can enable the view state to an individual control even if the view state for an 4S&.* T page is disabled.

Why do you use the A,,/0ode folder in +S4.N !? The .pp_Code folder is automatically present in the pro%ect. $t stores the files, such as classes, typed data set, text files, and reports. $f this folder is not available in the application, you can add this folder. !ne of the important features of the .pp_Code folder is that only one dll is created for the complete folder, irrespective of how many files it contains.

What is IIS? Why is it used? $nternet $nformation Services :$$S; is created by Microsoft to provide $nternet3based services to 4S&.* T Web applications. $t ma"es your computer to wor" as a Web server and provides the functionality to develop and deploy Web applications on the server. $$S handles the re#uest and response cycle on the Web server. $t also offers the services of SMT& and .ront&age server extensions. The SMT& is used to send emails and use .ront&age server extensions to get the dynamic features of $$S, such as form handler. What is 7uery Strin)? What are its ad.anta)es and limitations? The Guery String helps in sending the page information to the server. The Guery String has the following advantages, very browser wor"s with Guery Strings. $t does not re#uire server resources and so does not exert any "ind of burden on the server.

The following are the limitations of Guery String,

$nformation must be within the limit because 9<5 does not support many chara $nformation is clearly visible to the user, which leads to security threats.

What is tracin)? Where is it used? Tracing displays the details about how the code was executed. $t refers to collecting information about the application while it is running. Tracing information can help you to troubleshoot an application. $t enables you to record information in various log files about the errors that might occur at run time. +ou can analy2e these log files to find the cause of the errors. $n .* T, we have ob%ects called Trace 5isteners. 4 listener is an ob%ect that gets the trace output and stores it to different places, such as a window, a file on your locale drive, or a SG5 Server. The System!*iagnostics namespace contains the predefined interfaces, classes, and structures that are used for tracing. $t supplies two classes, Trace and 0ebug, which allow you to write errors and logs related to the application execution. Trace listeners are ob%ects that collect the output of tracing processes. What is the difference *et"een authentication and authori/ation? 4uthentication verifies the identity of a user and authori2ation is a process where you can chec" whether or not the identity has access rights to the system. $n other words, you can say that authentication is a procedure of getting some credentials from the users and verify the user's identity against those credentials. 4uthori2ation is a procedure of granting access of particular resources to an authenticated user. +ou should note that authentication always ta"es place before authori2ation. Differentiate )lo*ali/ation and locali/ation. The globali2ation is a techni#ue to identify the specific part of a Web application that is different for different languages and ma"e separate that portion from the core of the Web application. The locali2ation is a procedure of configuring a Web application to be supported for a specific language or locale. What is 1iew*tate? The $ie%State is a feature used by 4S&.* T Web page to store the value of a page and its controls %ust before posting the page. !nce the page is posted, the first tas" by the page processing is to restore the $ie%State to get the values of the controls. ,o" can you send an email messa)e from an +S4.N ! We* pa)e? +ou can use the System!Net!Mail!MailMessage and the System!Net!Mail!SmtpMail classes to send an email in your Web pages. $n order to send an email through your mail server, you need to create an ob%ect of the SmtpClient class and set the server name, port, and credentials. What is the difference *et"een the Res,onse.2rite(! and Res,onse.3ut,ut.2rite(! methods? The Response!"rite( method allows you to write the normal output@ whereas, theResponse!Gutput!"rite( method allows you to write the formatted output. Differentiate *et"een client-side and ser.er-side .alidations in We* pa)es. Client3side validations ta"e place at the client end with the help of >avaScript and ()Script before the Web page is sent to the server. !n the other hand, server3side validations ta"e place at the server end. What are ,!!4 handlers in +S4.N !? 8TT& handlers, as the name suggests, are used to handle user re#uests for Web application resources. They are the bac"bone of the re#uest3response model of Web applications. There is a specific event handler to handle the re#uest for each user re#uest type and send bac" the corresponding response ob%ect. ach user re#uests to the $$S Web server flows through the 8TT& pipeline, which refers to a series of

components :8TT& modules and 8TT& handlers; to process the re#uest. 8TT& modules act as filters to process the re#uest as it passes through the 8TT& pipeline. The re#uest, after passing through the 8TT& modules, is assigned to an 8TT& handler that determines the response of the server to the user re#uest. The response then passes through the 8TT& modules once again and is then sent bac" to the user. +ou can define 8TT& handlers in the E-ttpHandlers6 element of a configuration file. The Eadd6 element tag is used to add new handlers and the Eremove6 element tag is used to remove existing handlers. To create an 8TT& handler, you need to define a class that implements the )HttpHandler interface. What are the e.ents that happen "hen a client re8uests an +S4.N ! pa)e from IIS ser.er? The following events happen when a client re#uests an 4S&.* T page from the $$S server, -. 9ser re#uests for an application resource. 7. The integrated re#uest3processing pipeline receives the first user re#uest. L. Response ob%ects are created for each user re#uest.

M. C.

4n ob%ect of the Http.pplication class is created and allocated to the ReIuest ob%ect. The Http.pplication class processes the user re#uest.

What are the e.ent handlers that can *e included in the Glo*al.asa- file? The (lobal!asa, file contains some of the following important event handlers,

.pplication_+rror .pplication_Start .pplication_+nd Session_Start Session_+nd

Ma#e a list of all templates of the Re,eater control. The <epeater control contains the following templates,

)tem0emplate .lternatingltem0emplate Separator0emplate Header0emplate Cooter0emplate

Descri*e the complete lifecycle of a We* pa)e. When we execute a Web page, it passes from the following stages, which are collectively "nown as Web page lifecycle,

4a)e re8uest 3 0uring this stage, 4S&.* T ma"es sure the page either parsed or compiled and a cached version of the page can be sent in response Start 3 0uring this stage sets the <e#uest and <esponse page properties and the page chec" the page re#uest is either a postbac" or a new re#uest 4a)e Initiali/ation 3 0uring this stage, the page initiali2e and the control's 9ni#ue $d property are set $oad 3 0uring this stage, if the re#uest is postbac", the control properties are loaded without loading the view state and control state otherwise loads the view state 6alidation 3 0uring this stage, the controls are validated 4ost*ac# e.ent handlin) 3 0uring this stage, if the re#uest is a postbac", handles the event 1enderin) 3 0uring this stage, the page invo"es the <ender method to each control for return the output 9nload 3 0uring this stage, when the page is completely rendered and sent to the client, the page is unloaded.

What is a Coo#ie? Where is it used in +S4.N !?

Coo"ie is a lightweight executable program, which the server posts to client machines. Coo"ies store the identity of a user at the first visit of the Web site and validate them later on the next visits for their authenticity. The values of a coo"ie can be transferred between the user's re#uest and the server's response. What is the difference *et"een addin) items into cache throu)h the Add(! method and throu)h the4nsert(! method? )oth methods wor" in a similar way except that the Cac-e!.dd( function returns an ob%ect that represents the item you added in the cache. The Cac-e!)nsert( function can replace an existing item in the cache, which is not possible using the Cac-e!.dd( method. -plain the coo#ie less session and its "or#in). 4S&.* T manages the session state in the same process that processes the re#uest and does not create a coo"ie. $t is "nown as a coo"ie less session. $f coo"ies are not available, a session is trac"ed by adding a session identifier to the 9<5. The coo"ie less session is enabled using the following code snippet,EsessionState coo'ieless="true" 76

What is a round trip? The trip of a Web page from the client to the server and then bac" to the client is "nown as a round trip.

What are the ma:or *uilt-in o*:ects in +S4.N !? The ma%or built3in ob%ects in 4S&.* T are as follows,

.pplication ReIuest Response Server Session Conte,t 0race

What is the appSettin)s Section in the we5.con6ig file? The %eb!config file sets the configuration for a Web pro%ect. The appSettings bloc" in configuration file sets the user3defined values for the whole application. .or example, in the following code snippet, the specified ConnectionString section is used throughout the pro%ect for database connection,

Econfiguration6 EappSettings6 Eadd 'ey="ConnectionString" value="server=indiabi,server; p%d=dbpass%ord; database=indiabi," 76 E7appSettings6 !!!


What does the ;Ena5le1iew*tate; property do? Why do "e "ant it <n or <ff? The +nable$ie%State property enables the $ie%State property on the page. $t is set to !n to allow the page to save the users input between postbac" re#uests of a Web page@ that is, between the ReIuest and corresponding Response ob%ects. When this property is set to !ff, the page does not store the users input during postbac". Which e.ent determines that all the controls are completely loaded into memory? The :age_#oad event determines that all the controls on the page are fully loaded. +ou can also access

the controls in the :age_)nit event@ however, the $ie%State property does not load completely during this event. What is 1ole-*ased security? $n the <ole3based security, you can assign a role to every user and grant the privilege according to that role. 4 role is a group of principal that restricts a user's privileges. Therefore, all the organi2ation and applications use role3based security model to determine whether a user has enough privileges to perform a re#uested tas". What are the ,!M$ ser.er controls in +S4.N !? 8TM5 server controls are similar to the standard 8TM5 elements, which are normally used in 8TM5 pages. They expose properties and events that can be used programmatically. To ma"e these controls programmatically accessible, you need to specify that the 8TM5 controls act as a server control by adding the runat="server"attribute. Why a *ite7a,8ath control is referred to as *readcrum* or eye*ro" na.i)ation control? The SiteMap:at- control displays a hierarchical path to the root Web page of the Web site. Therefore, it is "nown as the breadcrumb or eyebrow navigation control.

Which namespaces are necessary to create a locali/ed application? The System!(lobaliDation and System!Resources namespaces are essential to develop a locali2ed application. What is the difference *et"een an 9tml4n,ut0heck.o: control and an 9tml4n,utRadio.utton control? +ou can select more than one Html)nputC-ec'&o, control from a group of Html)nputC-ec'&o, controls@ whereas, you can select only a single HtmllnputRadio&utton control from a group ofHtml)nputRadio&utton controls. -plain the AdRotator Control. The .dRotator is an 4S&.* T control that is used to provide advertisements to Web pages. The .dRotatorcontrol associates with one or many advertisements, which randomly displays one by one at a time when the Web page is refreshed. The .dRotator control advertisements are associated with lin"s@ therefore, when you clic" on an advertisement, it redirects you to other pages. The .dRotator control is associated with a data source, which is normally an xml file or a database table. 4 data source contains all the information, such as advertisement graphics reference, lin", and alternate text. Therefore, when you use the .dRotator control, you should first create a data source and then associate it with the .dRotator control. What do you understand *y the culture? The culture denotes a combination of a language and optionally a region or a country. The contents of a Web page of a multilingual Web site are changed according to the culture defined in the operating system of the user accessing the Web page. What is the code-*ehind feature in +S4.N !? The code3behind feature of 4S&.* T enables you to divide an 4S&.* T page into two files 3 one consisting of the presentation data, and the second, which is also called the code3behind file, consisting of all the business logic. The presentation data contains the interface elements, such as 8TM5 controls and Web server controls, and the code3behind contains the event3handling process to handle the events that are fired by these controls. The file that contains the presentation data has the .aspx extension. The code behind file has either the !cs extension :if you are using the programming language C#; or the !vb :if you are using the programming language (isual )asic .* T; extension. -plain the .alidation controls. ,o" many .alidation controls in +S4.N ! %.&?

(alidation controls are responsible to validate the data of an input control. Whenever you provide any input to an application, it performs the validation and displays an error message to user, in case the validation fails. 4S&.* T =.6 contains the following six types of validation controls,

Compare$alidator 3 &erforms a comparison between the values contained in two controls. Custom$alidator 3 Writes your own method to perform extra validation. Range$alidator3 Chec"s value according to the range of value. Regular+,pression$alidator 3 nsures that input is according to the specified pattern or
not.

ReIuiredCield$alidator 3 Chec"s either a control is empty or not. $alidationSummary 3 0isplays a summary of all validation error in a central location.
What is difference *et"een a $a*el control and a $iteral control? The 5abel control's final html code has an 8TM5 tag@ whereas, the 5iteral control's final html code contains only text, which is not surrounded by any 8TM5 tag. ,o" many types of Coo#ies are a.aila*le in +S4.N !? There are two types of Coo"ies available in 4S&.* T,

Session Coo#ie 3 <esides on the client machine for a single session until the user does not log out. 4ersistent Coo#ie 3 <esides on a user's machine for a period specified for its expiry, such as -6 days, one month, and never.

The user can set this period manually. What is the use of the ;lo5al.asa: file? The (lobal!asa, file executes application3level events and sets application3level variables. What are the Culture and 9ICulture .alues? The Culture value determines the functions, such as 0ate and Currency, which are used to format data and numbers in a Web page. The 9$Culture value determines the resources, such as strings or images, which are loaded for a Web page in a Web application.

What is the use of the (session*tate) ta) in the we5.con6ig file? The EsessionState6 tag is used to configure the session state features. To change the default timeout, which is 76 minutes, you have to add the following code snippet to the web.config file of an application,EsessionState timeout="JA"76 Which method do you use to #ill e-plicitly a users session? The Session!.bandon( method "ills the user session explicitly.

Which class is inherited "hen an +S4.N ! ser.er control is added to a We* form? The System!"eb!K)!"ebControls class is inherited when an 4S&.* T server control is added to a Web form. What e.ents are fired "hen a pa)e loads? The following events fire when a page loads,

)nit( 3 .ires when the page is initiali2ing. #oad$ie%State( 3 .ires when the view state is loading. #oad:ost*ata( 3 .ires when the postbac" data is processing.

#oad( 3 .ires when the page is loading. :reRender( 3 .ires at the brief moment before the page is displayed to the user as 8TM5. Knload( 3 .ires when the page is destroying the instances of server controls.
What are na.i)ation controls? ,o" many na.i)ation controls are there in +S4.N ! %.&? *avigation controls help you to navigate in a Web application easily. These controls store all the lin"s in a hierarchical or drop3down structure@ thereby facilitating easy navigation in a Web application. There are three navigation controls in 4S&.*et =.6.

SiteMap:at Menu 0ree$ie%


What is cross-pa)e postin) in +S4.N !? The Server!0ransfer( method is used to post data from one page to another. $n this case, the 9<5 remains the same. 8owever, in cross page posting, data is collected from different Web pages and is displayed on a single page. To do so, you need to set the :ost&ac'Krl property of the control, which specifies the target page. $n the target page, you can access the :revious:age property. .or this, you need to use theL:revious:age0ype directive. +ou can access the controls of previous page by using the CindControl( method. -plain the +pplication and Session o*:ects in +S4.N !. 4pplication state is used to store data corresponding to all the variables of an 4S&.* T Web application. The data in an application state is stored once and read several times. 4pplication state uses theHttp.pplicationState class to store and share the data throughout the application. +ou can access the information stored in an application state by using the Http.pplication class property. 0ata stored in the application state is accessible to all the pages of the application and is the same for all the users accessing the application. The Http.pplicationState class provides a loc" method, which you can use to ensure that only one user is able to access and modify the data of an application at any instant of time. ach client accessing a Web application maintains a distinct session with the Web server, and there is also some specific information associated with each of these sessions. Session state is defined in theEsessionState6 element of the %eb!config file. $t also stores the data specific to a user session in session variables. 0ifferent session variables are created for each user session. $n addition, session variables can be accessed from any page of the application. When a user accesses a page, a session $0 for the user is created. The session $0 is transferred between the server and the client over the 8TT& protocol using coo"ies. What are We* ser.er controls in +S4.N !? The 4S&.* T Web server controls are ob%ects on the 4S&.* T pages that run when the Web page is re#uested. Many Web server controls, such as button and text box, are similar to the 8TM5 controls. $n addition to the 8TM5 controls, there are many controls, which include complex behavior, such as the controls used to connect to data sources and display data. What are the .arious "ays of authentication techni8ues in +S4.N !? There are various techni#ues in 4S&.* T to authenticate a user. +ou can use one of the following ways of authentication to select a built3in authentication provider,

Windo"s +uthentication 3 This mode wor"s as the default authentication techni#ue. $t can wor" with any form of Microsoft $nternet $nformation Services :$$S; authentication, such as )asic, $ntegrated Windows authentication :*T5MHIerberos;, 0igest, and certificates. The syntax of Windows authentication mode is given as follows, Eaut-entication mode="%indo%s" 76 Forms +uthentication 3 +ou can specify this mode as a default authentication mode by using the following code snippet, Eaut-entication mode="Corms"76 4assport 3 This mode wor"s with Microsoft &assport authentication, as shown in the following

code snippet, Eaut-entication mode = ":assport"76

What is the use of "e*.confi)? What is the difference *et"een machine.confi) and "e*.confi)? 4S&.* T configuration files are AM53based text files for application3level settings and are saved with the name web.config. These files are present in multiple directories on an 4S&.* T Web application server. The%eb!config file sets the configuration settings to the directory it is placed in and to all the virtual sub folders under it. The settings in sub directories can optionally override or change the settings specified in the base directory. The difference between the %eb!config and mac-ine!config files is given as follows,

E"in*ir68Microsoft!N+08Crame%or'8Eversion68config8mac-ine!config provides
default configuration settings for the entire machine. 4S&.* T configures $$S to prohibit the browser directly from accessing the web.config files to ma"e sure that their values cannot be public. 4ttempts to access those files cause 4S&.* T to return the =6?, 4ccess .orbidden error. 4S&.* T uses these %eb!config configuration files at runtime to compute hierarchically a sole collection of settings for every 9<5 target re#uest. These settings compute only once and cached across further re#uests. 4S&.* T automatically chec"s for changing file settings and do not validate the cache if any of the configuration changes made. -plain the concept of states in +S4.N !. State is #uite an innovative concept in Web development because it eliminates the drawbac" of losing state data due to reloading of a Web page. )y using states in a Web application, you can preserve the state of the application either at the server or client end. The state of a Web application helps you to store the runtime changes that have been made to the Web application. .or example, as already described earlier, a change in the data source of the Web application might be initiated by a user when heHshe selects and saves some products in the shopping cart. $f you are not using states, these changes are discarded and are not saved. +ou may thin" that the whole concept of storing states is optional. 8owever, under certain circumstances, using states with applications is imperative. .or example, it is necessary to store states for Web applications, such as an e3commerce shopping site or an $ntranet site of a company, to "eep trac" of the re#uests of the users for the items they have selected on the shopping site or the days re#uested for vacation on the $ntranet site.

Can "e .alidate a DropDo"n$ist *y Re<uiredField1alidator? +es, we can validate a 0rop0own5ist by ReIuiredCield$alidator. To perform this validation, we have to set the )nitial$alue property of ReIuiredCield$alidator control.

&hat are Session state 'odes in ASP !"#$ A+0.5,T supports different session state storage options: (n)Process is the default approach. It stores session state locally on same web server memory where the application is running. StateSer*er mode stores session state in a process other than the one where application is running. 5aturally, it has added advantages that session state is accessible from multiple web servers in a 'eb Farm and also session state will remain preserved even web application is restarted. S+,Ser*er mode stores session state in +6/ +erver database. It has the same advantages as that of +tate+erver. Custo' modes allows to define our custom storage provider. -ff mode disables session storage.

5=8

1. E!plain #$% &#odel'$iew'%ontroller( in )eneral* &2, '&odel62iew6,ontroller) is an architectural software pattern that basically decouples various components of a web application. @y using &2, pattern" we can develop applications that are more fle*ible to changes without affecting the other components of our application. $,odel$, is basicall# domain data. $;iew$, is user inter ace to render domain data. $!ontroller$, translates user actions into appropriate operations per ormed on model. 2. What is 4SP.:E; 5=8? ASP./E# &2, is a web development framewor% from &icrosoft that is based on &2, '&odel62iew6,ontroller) architectural design pattern. &icrosoft has streamlined the development of &2, based applications using ASP./E# &2, framewor%. 3. %ifference bet,een 4SP.:E; 5=8 an( 4SP.:E; Web@or s? ASP./E# Beb Forms uses Page controller pattern approach for rendering layout" whereas ASP./E# &2, uses Front controller approach. n case of Page controller approach" every page has its own controller i.e. code6behind file that processes the re1uest. On the other hand" in ASP./E# &2," a common controller for all pages processes the re1uests. Follow the lin% for the difference between the ASP./E# &2, and ASP./E# BebForms. ". +,at are t,e %ore features of ASP.-E. #$%* !ore eatures o ASP.6E( ,;! ramework are0 !lear separation o application concerns (Presentation and :usiness <ogic) An e"tensible and pluggable ramework E"tensi&e support or ASP.6E( =outing Support or e"isting ASP.6E( eatures 1ollow or detailed understanding o abo&e mentioned core eatures. /. %an 0ou please e!plain t,e re1uest flow in ASP.-E. #$% framewor2* =e3uest low or ASP.6E( ,;! ramework is as ollows0 =e3uest hits the controller coming rom client. !ontroller pla#s its role and decides which model to use in order to ser&e the re3uest. 1urther passing that model to &iew which then trans orms the model and generate an appropriate response that is rendered to client. 6. What is Eoutin) in 4SP.:E; 5=8? /n case o a t#pical ASP.6E( application, incoming re3uests are mapped to ph#sical iles such as .asp" ile. ASP.6E( ,;! ramework uses riendl# 5=<s that more easil# describe user>s action but not mapped to ph#sical iles. ASP.6E( ,;! ramework uses a routing engine, that maps 5=<s to controller classes. %e can de ine routing rules or the engine, so that it can map incoming re3uest 5=<s to appropriate controller. Practicall#, when a user t#pes a 5=< in a browser window or an ASP.6E( ,;! application and presses ?go@ button, routing engine uses routing rules that are de ined in 7lobal.asa" ile in order to parse the 5=< and ind out the path o corresponding controller. 3. +,at is t,e difference between $iewData4 $iewBa) and .empData* /n order to pass data rom controller to &iew and in ne"t subse3uent re3uest, ASP.6E( ,;! ramework pro&ides di erent options i.e. ;iewAata, ;iew:ag and (empAata. :oth ;iew:ag and ;iewAata are used to to communicate between controller and corresponding &iew.:ut this communication is onl# or ser&er call, it becomes null i redirect occurs. So, in short, its a mechanism to maintain state between controller and corresponding &iew.

;iewAata is a dictionar# object while ;iew:ag is a d#namic propert# (a new !8 B.C eature). &iewAata being a dictionar# object is accessible using strings as ke#s and also re3uires t#pecasting or comple" t#pes.On the other hand, ;iew:ag doesn4t ha&e t#pecasting and null checks. (empAata is also a dictionar# object that sta#s or the time o an 2((P =e3uest. So, (empdata can be used to maintain data between redirects i.e rom one controller to the other controller.

5. +,at are Action #et,ods in ASP.-E. #$%* As / alread# e"plained about re3uest low in ASP.6E( ,;! ramework that re3uest coming rom client hits controller irst. Actuall# ,;! application determines the corresponding controller b# using routing rules de ined in 7lobal.asa". And controllers ha&e speci ic methods or each user actions. Each re3uest coming to controller is or a speci ic Action ,ethod. (he ollowing code e"ample, ?Show:ooks@ is an e"ample o an Action ,ethod. public ;iew=esult Show:ooks(int id) * &ar computer:ook . db.:ooks.%here(p .D P.:ook/A .. id).1irst()+ return ;iew(computer:ook)+ -

6.E!plain t,e role of #odel in ASP.-E. #$%* One o the core eature o ASP.6E( ,;! is that it separates the input and 5/ logic rom business logic. =ole o ,odel in ASP.6E( ,;! is to contain all application logic including &alidation, business and data access logic e"cept &iew i.e. input and controller i.e 5/ logic. ,odel is normall# responsible or accessing data rom some persistent medium like database and manipulate it. 17.+,at are Action 8ilters in ASP.-E. #$%* / we need to appl# some speci ic logic be ore or a ter action methods, we use action ilters. %e can appl# these action ilters to a controller or a speci ic controller action. Action ilters are basicall# custom classes that pro&ide a mean or adding pre'action or post'action beha&ior to controller actions. 1or e"ample, AuthoriEe ilter can be used to restrict access to a speci ic user or a role. Output!ache ilter can cache the output o a controller action or a speci ic duration.

What are routin) in 5=8? .outing helps you to define a E.$ structure and map the E.$ with the controller. For instance letAs say we want that when any user types Phttp:!!localhost!2iew!2iew,ustomer!X " it goes to the P,ustomerX ,ontroller and invo%es P0isplay,ustomerX action. #his is defined by adding an entry in to the ProutesX collection using the PmaprouteX function. @elow is the under lined code which shows how the E.$ structure and mapping with controller and action is defined. routes.&ap.oute' J2iewJ" !! .oute name

J=ie,3=ie,8usto er!8id9J" !! E.$ with parameters new 8 controller I A8usto erA2 action I A%isplay8usto erA" id : ErlParameter.Optional 9)5 !! Parameter defaults Where is the route appin) co(e ,ritten? #he route mapping code is written in the Pglobal.asa*X file. 8an ,e ap ultiple <EH0s to the sa e action? Des " you can " you just need to ma%e two entries with different %ey names and specify the same controller and action. .o, can ,e na'i)ate fro one 'ie, to other 'ie, usin) hyperlin+? @y using PAction$in%X method as shown in the below code. #he below code will create a simple E.$ which help to navigate to the PFomeX controller and invo%e the PNotoFomeX action. ([: Ftml.Action$in%'JFomeJ"JNotohomeJ) [+ .o, can ,e restrict 5=8 actions to be in'o+e( only by GE; or POS;? Be can decorate the &2, action by PFttpNetX or PFttpPostX attribute to restrict the type of F##P calls. For instance you can see in the below code snippet the P0isplay,ustomerX action can only be invo%ed by PFttpNetX. f we try to ma%e Fttp post on P0isplay,ustomerX it will throw an error. TFttpNetU public 2iew.esult 0isplay,ustomer'int id) 8 ,ustomer obj,ustomer : ,ustomersTidU5 return 2iew'J0isplay,ustomerJ"obj,ustomer)5 9 .o, can ,e aintain session in 5=8? Sessions can be maintained in &2, by L ways tempdata "viewdata and viewbag.
;e p (ata9 BFelps to maintain data when you move from one controller to other controller or from one action to other action. n other words when you redirect"PtempdataX helps to maintain data between those redirects. t internally uses session variables. =ie, (ata9 B Felps to maintain data when you move from controller to view. =ie, ?a)9 B tAs a dynamic wrapper around view data. Bhen you use P2iewbagX type casting is not re1uired. t uses the dynamic %eyword internally. Session 'ariables: 6 @y using session variables we can maintain data from any entity to any entity. .i((en fiel(s an( .;5H controls: 6 Felps to maintain data from E to controller only. So you can send data from F#&$ controls or hidden fields to the controller using POS# or NE# F##P methods.

Partial 'ie, Partial view is a reusable view 'li%e a user control) which can be embedded inside other view. For e*ample letAs say all your pages of your site have a standard structure with left menu" header and footer. .o, can ,e (o 'ali(ations in 5=8?

One of the easy ways of doing validation in &2, is by using data annotations. 0ata annotations are nothing but attributes which you can be applied on the model properties. For e*ample in the below code snippet we have a simple PcustomerX class with a property PcustomercodeX. #hisX,ustomer,odeX property is tagged with a P.e1uiredX data annotation attribute. n other words if this model is not provided customer code it will not accept the same. public class ,ustomer 8 T.e1uired'Error&essage:J,ustomer code is re1uiredJ)U public string ,ustomer,ode 8 set5 get5 9 9 What is ra*or in5=8? tAs a light weight view engine. #ill &2, we had only one view type i.e.ASP\" .a-or was introduced in &2, L. Why ra*or ,hen ,e alrea(y ha( 4SPJ? .a-or is clean" lightweight and synta*es are easy as compared to ASP\. For e*ample in ASP\ to display simple time we need to write. ([:0ate#ime./ow[+ n .a-or itAs just one line of code. ]0ate#ime./ow So ,hich is a better fit Ea*or or 4SPJ? As per &icrosoft ra-or is more preferred because itAs light weight and has simple synta*es. @ut my suggestion would be to answer more realtime^. What is the (ifference bet,een C4ctionEesultD an( C=ie,EesultD? PAction.esultX is an abstract class while P2iew.esultX derives from PAction.esultX class. PAction.esultX has several derived classes li%e P2iew.esultX "XRson.esultX " PFileStream.esultX and so on. PAction.esultX can be used to e*ploit polymorphism and dynamism. So if you are returning different types of view dynamically PAction.esultX is the best thing. For e*ample in the below code snippet you can see we have a simple action called as P0ynamic2iewX. 0epending on the flag 'P sFtml2iewX) it will either return P2iew.esultX or PRson.esultX. public Action.esult 0ynamic2iew') 8 if ' sFtml2iew) return 2iew')5 !! returns simple 2iew.esult else return Rson')5 !! returns Rson.esult view 9

What are the (ifferent types of results in 5=8? #here ;< %inds of results in &2," at the top is PAction.esultXclass which is a base class that canhave;;subtypesAsas listed below: 6 ;. 2iew.esult 6 .enders a specified view to the response stream <. Partial2iew.esult 6 .enders a specified partial view to the response stream L. Empty.esult 6 An empty response is returned M. .edirect.esult 6 Performs an F##P redirection to a specified E.$ C. .edirect#o.oute.esult 6 Performs an F##P redirection to a E.$ that is determined by the routing engine" based on given route data =. Rson.esult 6 Seriali-es a given 2iew0ata object to RSO/ format Y. RavaScript.esult 6 .eturns a piece of RavaScript code that can be e*ecuted on the client S. ,ontent.esult 6 Brites content to the response stream without re1uiring a view W. File,ontent.esult 6 .eturns a file to the client ;G. FileStream.esult 6 .eturns a file to the client" which is provided by a Stream ;;. FilePath.esult 6 .eturns a file to the client What are the benefits of usin) 5=8?
There are two big benefits of .*1: +eparation of concerns is achieved as we are moving the code&behind to a separate class file. !y moving the binding code to a separate class file we can reuse the code to a great extent. Automated 3I testing is possible because now the behind code <3I interaction code= has moved to a simple .5,T class. This gives us opportunity to write unit tests and automate manual testing.

Bhat is the difference between each version of &2,Q @elow is a detailed table of differences. @ut during an interview itAs difficult to tal% about all of them due to time limitation. So have highlighted the important differences that you can run through before the interviewer. 5=8 2 5=8 3 5=8 4 8lientBsi(e 'ali(ation Ea*or 4SP.:E; Web 4P" ;e plate( .elpers 4reas .eadymade project .efreshed and moderni-ed templates default project templates. 4synchronous 8ontrollers /ew mobile project .;5H 5 enable( Ftml.2alidationSummary Felper &ethod template. 0efault2alueAttribute in Action6&ethod te plates Support for 5ultiple 5any ne, features to Parameters binding support obile apps =ie, En)ines2 @inary data with &odel @inders Ka'aScript2 an( 4K4J Enhanced support for 0ataAnnotations Attributes asynchronous methods &odel 2alidation &odel62alidator Providers mprovements /ew .e1uireFttpsAttributeAction Filter #emplated Felpers 0isplay &odel6$evel Errors Bhat is the difference between PF#&$.#e*t@o*X vs PF#&$.#e*t@o*ForXQ
!oth of them provide the same 2T./ output, ?2T./.Text!oxFor@ is strongly typed while ?2T./.Text!ox@ isn>t. !elow is a simple 2T./ code which "ust creates a simple textbox with ?1ustomer1ode@ as name.

Gt"l.#e@t3o@("Custo"erCode")

!elow is ?2tml.Text!oxFor@ code which creates 2T./ textbox using the property name A1ustomer1ode@ from ob"ect ?m@.

Gt"l.#e@t3o@7or(" -I ".Custo"erCode)

In the same way we have for other 2T./ controls li$e for chec$box we have ?2tml.1hec$!ox@ and ?2tml.1hec$!oxFor@.

Bhat is routing in &2,Q


Bouting helps you to define a 3B/ structure and map the 3B/ with the controller. For instance let>s say we want that when a user types ?http:CClocalhostC*iewC*iew1ustomerC@, it goes to the ?1ustomer@ 1ontroller and invo$es the )ispla!Custo"er action. This is defined by adding an entry in to the routescollection using the "aproute function. !elow is the underlined code which shows how the 3B/ structure and mapping with controller and action is defined.
1ollapse D ,opy ,ode

routes.Map5oute( "Jie$"& // +oute name "Jie$8Jie$Custo"er8{id}"& // ,+* with parameters ne$ { controller - "Custo"er"& action - ")ispla!Custo"er"& id - Lrl2ara"eter.9ptional }); // -arameter defaults

Bhere is the route mapping code writtenQ #he route mapping code is written in the Pglobal.asa*X file. ,an we map multiple E.$As to the same actionQ Des" you can" you just need to ma%e two entries with different %ey names and specify the same controller and action. Fow can we navigate from one view to another using a hyperlin%Q @y using the Action$in% method as shown in the below code. #he below code will create a simple E.$ which helps to navigate to the PFomeX controller and invo%e the NotoFome action. ([: Ftml.Action$in%'JFomeJ"JNotohomeJ) [+ Fow can we restrict &2, actions to be invo%ed only by NE# or POS#Q Be can decorate the &2, action with the FttpNet or FttpPost attribute to restrict the type of F##P calls. For instance you can see in the below code snippet the 0isplay,ustomer action can only be invo%ed by FttpNet. f we try to ma%e F##P POS# on 0isplay,ustomer" it will throw an error. TFttpNetU public 2iew.esult 0isplay,ustomer'int id) 8 ,ustomer obj,ustomer : ,ustomersTidU5

return 2iew'J0isplay,ustomerJ"obj,ustomer)5 9

Fow can we maintain sessions in &2,Q Sessions can be maintained in &2, by three ways: tempdata" viewdata" and viewbag.
Temp data & 2elps to maintain data when you move from one controller to another controller or from one action to another action. In other words when you redirect, tempdata helps to maintain data between those redirects. It internally uses session variables. &hat is the difference bet.een te'pdata/ *ie.data/ and *ie.ba%$

*iew data & 2elps to maintain data when you move from controller to view. *iew !ag & It>s a dynamic wrapper around view data. 'hen you use Jie$bag type, casting is not
re:uired. It uses the d!na"ic $eyword internally. +ession variables & !y using session variables we can maintain data from any entity to any entity. data from 2T./ controls or hidden fields to the controller using 0 +T or E,T 2TT0 methods.

2idden fields and 2T./ controls & 2elps to maintain data from 3I to controller only. +o you can send

Bhat are the new features of &2,LQ ASP./E# &2, L shipped just ;G months after &2, < in Ran <G;;. Some of the top features in &2, L included: #he .a-or view engine Support for ./E# M 0ata Annotations mproved model validation Nreater control and fle*ibility with support for dependency resolution and global action filters @etter RavaScript support with unobtrusive RavaScript" jVuery 2alidation" and RSO/ binding Ese of /uNet to deliver software and manage dependencies throughout the platform Bhat are the new features of &2,MQ Following are the top features of &2,M: ASP./E# Beb AP Enhancements to default project templates &obile project template using jVuery &obile 0isplay &odes #as% support for Asynchronous ,ontrollers @undling and minification E*plain Ppage lifecycleX of an ASP./E# &2,Q Following processes are performed by ASP./E# &2, page: ;.App initiali-ation <..outing L. nstantiate and e*ecute controller M.$ocate and invo%e controller action C. nstantiate and render view

Advantages of &2, Framewor%Q ;.Provides a clean separation of concerns between E 'Presentation layer)" model '#ransfer objects!0omain Objects!Entities) and @usiness $ogic ',ontroller) <.Easy to E/ # #est L. mproved reusability of views!model. One can have multiple views which can point to the same model and vice versa M. mproved structuring of the code Bhat do you mean by Separation of ,oncernsQ As per Bi%ipedia" Kthe process of brea%ing a computer program into distinct features that overlap in functionality as little as possibleK. &2, design pattern aims to separate content from presentation and data6processing from content. Bhere do we see Separation of ,oncerns in &2,Q @etween the data6processing '&odel) and the rest of the application. Bhen we tal% about 2iews and ,ontrollers" their ownership itself e*plains separation. #he views are just the presentation form of an application" it does not have to %now specifically about the re1uests coming from controller. #he &odel is independent of 2iew and ,ontrollers" it only holds business entities that can be passed to any 2iew by the controller as re1uired for e*posing them to the end user. #he controller is independent of 2iews and &odels" its sole purpose is to handle re1uests and pass it on as per the routes defined and as per the need of rendering views. #hus our business entities 'model)" business logic 'controllers) and presentation logic 'views) lie in logical!physical layers independent of each other. Bhat is .a-or 2iew EngineQ .a-or is the first major update to render F#&$ in &2,L. .a-or was designed specifically as a view engine synta*. t has one main focus: code6focused templating for F#&$ generation. FereAs how that same mar%up would be generated using .a-or: Bhat is Enobtrusive RavaScriptQ Enobtrusive RavaScript is a general term that conveys a general philosophy" similar to the term .ES# '.epresentational State #ransfer). #he high6level description is that unobtrusive RavaScript doesnAt intermi* RavaScript code in your page mar%up. For e*ample" rather than hoo%ing in via event attributes li%e onclic% and onsubmit" the unobtrusive RavaScript attaches to elements by their 0 or class" often based on the presence of other attributes 'such as F#&$C data6 attributes). tAs got semantic meaning" and all of it _ the tag structure" element attributes" and so on _ should have a precise meaning. Strewing RavaScript gun% across the page to facilitate interaction ' Am loo%ing at you" IIdoPost@ac%`) harms the content of the document. Bhat is RSO/ @indingQ &2, L included RavaScript Object /otation 'RSO/) binding support via the new Rson2alueProviderFactory" enabling the action methods to accept and model6bind data in RSO/ format. #his is especially useful in advanced Aja* scenarios li%e client templates and data binding that need to post data bac% to the server.

Bhat is 0ependency .esolutionQ &2, L introduced a new concept called a dependency resolver" which greatly simplified the use of dependency injection in your applications. #his made it easier to decouple application components" ma%ing them more configurable and easier to test. Support was added for the following scenarios: ,ontrollers 'registering and injecting controller factories" injecting controllers) 2iews 'registering and injecting view engines" injecting dependencies into view pages) Action filters 'locating and injecting filters) &odel binders 'registering and injecting) &odel validation providers 'registering and injecting) &odel metadata providers 'registering and injecting) 2alue providers 'registering and injecting) Bhat are 0isplay &odes in &2,MQ 0isplay modes use a convention6based approach to allow selecting different views based on the browser ma%ing the re1uest. #he default view engine first loo%s for views with names ending with .&obile.cshtml when the browserAs user agent indicates a %nown mobile device. For e*ample" if we have a generic view titled nde*.cshtml and a mobile view titled nde*.&obile.cshtml" &2, M will automatically use the mobile view when viewed in a mobile browser. Additionally" we can register your own custom device modes that will be based on your own custom criteria _ all in just one code statement. For e*ample" to register a BinPhone device mode that would serve views ending with.BinPhone.cshtml to Bindows Phone devices" youAd use the following code in the ApplicationIStart method of your Nlobal.asa*: Bhat are the differences between 2iew0ata and 2iew@agQ 'ta%en from a blog) 2iew0ata is a dictionary of objects that is derived from 2iew0ata0ictionary class and accessible usingstrings as %eys. 2iew@ag is a dynamic property that ta%es advantage of the new dynamic features in ,O M.G. 2iew0ata re1uires typecasting for comple* data type and chec%s for null values to avoid error. 2iew@ag doesnAt re1uire typecasting for comple* data type. /O#E: Although there might not be a technical advantage to choosing one format over the other" there are some critical differences to be aware of between the two synta*es. One obvious difference is that 2iew@ag wor%s only when the %ey being accessed is a valid ,O identifier. For e*ample" if you place a value in 2iew0ataTJ?eyBith SpacesJU" you canAt access that value using 2iew@ag because the codewonAt compile. Another %ey issue to be aware of is that dynamic values cannot be passed in as parameters to e*tension methods. #he ,O compiler must %now the real type of every parameter at compile time in order for it to choose the correct e*tension method. f any parameter is dynamic" compilation will fail. For e*ample" this code will always fail: ]Ftml.#e*t@o*'JnameJ" 2iew@ag./ame). #o wor% around this" either use 2iew0ataTJ/ameJU or cast the value to a specific type: 'string) 2iew@ag./ame. Bhat is #emp0ataQ #emp0ata is a dictionary derived from the #emp0ata0ictionary class and stored in short lives session. t is astring %ey and object value. t %eeps the information for the time of an F##P .e1uest. #his means only from one page to another. t helps to maintain data when we move from one controller to another controller or from one action to other action. n other words" when we redirect #empdata helps to maintain data

between those redirects. t internally uses session variables. #emp data use during the current and subse1uent re1uest only means it is used when we are sure that the ne*t re1uest will be redirecting to ne*t view. t re1uires typecasting for comple* data type and chec%s for null values to avoid error. Nenerally it is used to store only one time messages li%e error messages" validation messages. E*plain .outing in &2,Q
A route is a 3B/ pattern that is mapped to a handler. The handler can be a physical file, such as an .aspx file in a 'eb Forms application. Bouting module is responsible for mapping incoming browser re:uests to particular .*1 controller actions. Bouting within the A+0.5,T .*1 framewor$ serves two main purposes: It matches incoming re:uests that would not otherwise match a file on the file system and maps the re:uests to a controller action. It constructs outgoing 3B/s that correspond to controller actions.

What are Hayouts in 4SP.:E; 5=8 Ea*or? $ayouts in .a-or help maintain a consistent loo% and feel across multiple views within our application. As compared to Beb Forms" layouts serve the same purpose as master pages" but offer both a simpler synta* and greater fle*ibility. Be can use a layout to define a common template for your site 'or just part of it). #his template contains one or more placeholders that the other views in your application provide content for. n some ways" itAs li%e an abstract base class for your views. E.g. declared at the top of view as: ]8 $ayout : Ja!2iews!Shared!Site$ayout.cshtmlJ5 9 What is =ie,Start? For group of views that all use the same layout" this can get a bit redundant and harder to maintain. #he I2iewStart.cshtml page can be used to remove this redundancy. #he code within this file is e*ecuted before the code in any view placed in the same directory. #his file is also recursively applied to any view within a subdirectory. Bhen we create a default ASP./E# &2, project" we find there is already a I2iewStart .cshtml file in the 2iewsdirectory. t specifies a default layout: ]8 $ayout : Ja!2iews!Shared!I$ayout.cshtmlJ5 9 @ecause this code runs before any view" a view can override the $ayout property and choose a different one. f a set of views shares common settings" the I2iewStart.cshtml file is a useful place to consolidate these common view settings. f any view needs to override any of the common settings" the view can set those values to another value. /ote: Some of the content has been ta%en from various boo%s!articles. What are .;5H .elpers? F#&$ helpers are methods we can invo%e on the F#&$ property of a view. Be also have access to E.$ helpers 'via the Erl property)" and ARA\ helpers 'via the Aja* property). All these helpers

have the same goal: to ma%e views easy to author. #he E.$ helper is also available from within the controller. &ost of the helpers" particularly the F#&$ helpers" output F#&$ mar%up. For e*ample" the @eginForm helper is a helper we can use to build a robust form tag for our search form" but without using lines and lines of code: ]using 'Ftml.@eginForm'JSearchJ" JFomeJ" Form&ethod.Net)) 8 (input type:Jte*tJ name:J1J !+ (input type:JsubmitJ value:JSearchJ !+ 9 What is .t l.=ali(ationSu ary? #he 2alidationSummary helper displays an unordered list of all validation errors in the &odelState dictionary. #he @oolean parameter you are using 'with a value of true) is telling the helper to e*clude property6level errors. n other words" you are telling the summary to display only the errors in &odelState associated with the model itself" and e*clude any errors associated with a specific model property. Be will be displaying property6level errors separately. Assume you have the following code somewhere in the controller action rendering the edit view: &odelState.Add&odelError'JJ" J#his is all wrong`J)5 &odelState.Add&odelError'J#itleJ" JBhat a terrible name`J)5 #he first error is a model6level error" because you didnAt provide a %ey 'or provided an empty %ey) to associate the error with a specific property. #he second error you associated with the #itle property" so in your view it will not display in the validation summary area 'unless you remove the parameter to the helper method" or change the value to false). n this scenario" the helper renders the following F#&$: (div class:Jvalidation6summary6errorsJ+ (ul+ (li+#his is all wrong`(!li+ (!ul+ (!div+ Other overloads of the 2alidationSummary helper enable you to provide header te*t and set specific F#&$ attributes. /O#E: @y convention" the 2alidationSummary helper renders the ,SS class validation6summary6 errors along with any specific ,SS classes you provide. #he default &2, project template includes some styling to display these items in red" which you can change in styles.css. What are =ali(ation 4nnotations? 0ata annotations are attributes you can find in System.,omponent&odel.0ataAnnotations namespace. #hese attributes provide server6side validation" and the framewor% also supports client6side validation when you use one of the attributes on a model property. Dou can use four attributes in the 0ataAnnotations namespace to cover common validation scenarios" .e1uired" String $ength" .egular E*pression" .ange. What is .t l.Partial? #he Partial helper renders a partial view into a string. #ypically" a partial view contains reusable mar%up you want to render from inside multiple different views. Partial has four overloads: public void Partial'string partial2iew/ame)5 public void Partial'string partial2iew/ame" object model)5

public void Partial'string partial2iew/ame" 2iew0ata0ictionary view0ata)5 public void Partial'string partial2iew/ame" object model" 2iew0ata0ictionary view0ata)5 What is .t l.Een(erPartial? #he .enderPartial helper is similar to Partial" but .enderPartial writes directly to the response output stream instead of returning a string. For this reason" you must place .enderPartial inside a code bloc% instead of a code e*pression. #o illustrate" the following two lines of code render the same output to the output stream: ]8Ftml..enderPartial'JAlbum0isplay J)5 9 ]Ftml.Partial'JAlbum0isplay J) "f they are the sa e2 then ,hich one to use? n general" you should prefer Partial to .enderPartial because Partial is more convenient 'you donAt have to wrap the call in a code bloc% with curly braces). Fowever" .enderPartial may result in better performance because it writes directly to the response stream" although it would re1uire a lot of use 'either high site traffic or repeated calls in a loop) before the difference would be noticeable. .o, (o you return a partial 'ie, fro controller?

return Partial2iew'options)5 //o*tions could be .odel or -iew name Bhat are different ways of returning a 2iewQ #here are different ways for returning!rendering a view in &2, .a-or. E.g. return 2iew')" return.edirect#oAction')" return .edirect') and return .edirect#o.oute'). SLH Ser'er "nner Koin nner join is the most common type of Roin which is used to combine the rows from two tables and create a result set containing only such records that are present in both the tables based on the joining condition 'predicate). $nner join returns rows when there is at least one match in both tables f none of the record matches between two tables" then //E. RO / will return a /E$$ set. @elow is an e*ample of //E. RO / and the resulting set. SE$E,# dept.name 0EPA.#&E/#" emp.name E&P$ODEE F.O& 0EP# dept" E&P$ODEE emp BFE.E emp.deptIid : dept.id Outer Koin

Outer Roin" on the other hand" will return matching rows from both tables as well as any unmatched rows from one or both the tables 'based on whether it is single outer or full outer join respectively).

Outer Join can be full outer or single outer

/otice in our record set that there is no employee in the department C '$ogistics). @ecause of this if we perform inner join" then 0epartment C does not appear in the above result. Fowever in the below 1uery we perform an outer join 'dept left outer join emp)" and we can see this department. SE$E,# dept.name 0EPA.#&E/#" emp.name E&P$ODEE F.O& 0EP# dept" E&P$ODEE emp BFE.E dept.id : emp.deptIid '3) What is the difference between JOIN and UNION?
SQL JOIN allows us to lookup records on other table based on the given conditions between two tables. For e a!ple" i# we have the depart!ent I$ o# each e!plo%ee" then we can use this depart!ent I$ o# the e!plo%ee table to &oin with the depart!ent I$ o# depart!ent table to lookup depart!ent na!es. 'NION operation allows us to add ( si!ilar data sets to create resulting data set that contains all the data #ro! the source data sets. 'nion does not re)uire an% condition #or &oining. For e a!ple" i# %ou have ( e!plo%ees #ro! both o# the tables. e!plo%ee tables with sa!e structure" %ou can 'NION the! to create one result set that will contain all the

S+#+C0 M CRGM +M:B KN)GN S+#+C0 M CRGM +M:F;

What is the difference between UNION and UNION ALL?


'NION and 'NION *LL both uni#% #or add two structurall% si!ilar data sets" but 'NION operation returns onl% the uni)ue records #ro! the resulting data set whereas 'NION *LL will return all the rows" even i# one or !ore rows are duplicated to each other. In the #ollowing e a!ple" I a! choosing e actl% the sa!e e!plo%ee #ro! the e!p table and per#or!ing 'NION and 'NION *LL. +heck the di##erence in the result.

S+#+C0 M CRGM +M:#GN++ "H+R+ )* = O KN)GN .## S+#+C0 M CRGM +M:#GN++ "H+R+ )* = O S+#+C0 M CRGM +M:#GN++ "H+R+ )* = O KN)GN

S+#+C0 M CRGM +M:#GN++ "H+R+ )* = O

What is the difference between WHERE clause and HAVING clause?


,-./. and -*0IN1 both #ilters out records based on one or !ore conditions. 2he di##erence is" ,-./. clause can onl% be applied on a static non3aggregated colu!n whereas we will need to use -*0IN1 #or aggregated colu!ns. 2o understand this" consider this e a!ple.

Suppose we want to see onl% those depart!ents where depart!ent I$ is greater than 4. 2here is no aggregation operation and the condition needs to be applied on a static #ield. ,e will use ,-./. clause here5

S+#+C0 M CRGM *+:0 "H+R+ )* 6 > ,e will need to use -*0IN1 clause here5 S+#+C0 dept!name *+:.R0M+N0? avg(emp!sal CRGM *+:0 dept? +M:#GN++ emp "H+R+ dept!id = emp!dept_id (9 (RGK: &N dept!name H.$)N( .$((emp!sal 6 PA .$(_S.#

What is the difference am n! UNION" #INU$ and IN%ER$E&%?


'NION co!bines the results #ro! ( tables and eli!inates duplicate records #ro! the result set. 6IN'S operator when used between ( tables" gives us all the rows #ro! the #irst table e cept the rows which are present in the second table. IN2./S.+2 operator returns us onl% the !atching or co!!on rows between ( result sets. 2o understand these operators" let7s see so!e e a!ples. ,e will use two di##erent )ueries to e tract data data.

#ro! our e!p table and then we will per#or! 'NION" 6IN'S and IN2./S.+2 operations on these two sets o#

UNION
S+#+C0 M CRGM +M:#GN++ "H+R+ )* = O KN)GN S+#+C0 M CRGM +M:#GN++ "H+R+ )* = Q

MINUS
S+#+C0 M CRGM +M:#GN++

M)NKS S+#+C0 M CRGM +M:#GN++ "H+R+ )* 6 F

INTERSECT
S+#+C0 M CRGM +M:#GN++ "H+R+ )* )N (F? >? O )N0+RS+C0 S+#+C0 M CRGM +M:#GN++ "H+R+ )* )N (B? F? J? O

What is $elf J in and wh' is it re(uired?


Sel# Join is the act o# &oining one table with itsel#.

Self Join is often very useful to convert a hierarchical structure into a flat structure
In our e!plo%ee table e a!ple above" we have kept the !anager I$ o# each e!plo%ee in the sa!e row as that o# the e!plo%ee. 2his is an e a!ple o# how a hierarch% 8in this case e!plo%ee3!anager hierarch%9 is stored in the /$:6S table. Now" suppose i# we need to print out the na!es o# the !anager o# each e!plo%ee right beside the e!plo%ee" we can use sel# &oin. See the e a!ple below5

S+#+C0 e!name +M:#GN++? m!name M.N.(+R CRGM +M:#GN++ e? +M:#GN++ m "H+R+ e!mgr_id = m!id (9 2he onl% reason we have per#or!ed a le#t outer &oin here 8instead o# INN./ JOIN9 is we have one e!plo%ee in this table without a !anager 8e!plo%ee I$ ; <9. I# we per#or! inner &oin" this e!plo%ee will not show3up.

H w can we trans) se a table usin! $*L +chan!in! r ws t c lumn r ,ice-,ersa. ?


2he usual wa% to do it in SQL is to use +*S. state!ent or $.+O$. state!ent.

H w t !enerate r w number in $*L With ut ROWNU#


1enerating a row nu!ber = that is a running se)uence o# nu!bers #or each row is not eas% using plain SQL. least one uni)ue colu!n in the table. 2his !ethod will also work i# there is no single uni)ue colu!n" but collection o# colu!ns that is uni)ue. *n%wa%" here is the )uer%5 In #act" the !ethod I a! going to show below is not ver% generic either. 2his !ethod onl% works i# there is at

S+#+C0 name? sal? (S+#+C0 CGKN0(M CRGM +M:#GN++ o

CRGM +M:#GN++ i "H+R+ o!name 6= i!name

ro%_num

order by ro%_num What are the difference *et"een clustered and a non-clustered inde-?

;. <.

+ clustered inde- is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages. + non clustered inde- is a special type of index in which the logical order of the index does not match the physical stored order of the rows on dis". The leaf node of a non clustered index does not consist of the data pages. $nstead, the leaf nodes contain index rows.

8lustere( "n(e#he primary %ey created for the Stud d column will create a clustered inde* for the Studid column. A table can have only one clustered inde* on it. Bhen creating the clustered inde*" SV$ server <GGC reads the Studid column and forms a @inary tree on it. #his binary tree information is then stored separately in the disc. E*pand the table Student and then e*pand the nde*es. Dou will see the following inde* created for you when the primary %ey is created: Bith the use of the binary tree" now the search for the student based on the studid decreases the number of comparisons to a large amount. $et us assume that you had entered the following data in the table student: #he inde* will form the below specified binary tree. /ote that for a given parent" there are only one or two ,hilds. #he left side will always have a lesser value and the right side will always have a greater value when compared to parent. #he tree can be constructed in the reverse way also. #hat is" left side higher and right side lower. /ow let us assume that we had written a 1uery li%e below: Select 7 from student where studid : ;GL5 Select 7 from student where studid : ;GY5 E*ecution without inde* will return value for the first 1uery after third comparison. E*ecution without inde* will return value for the second 1uery at eights comparison. E*ecution of first 1uery with inde* will return value at first comparison. E*ecution of second 1uery with inde* will return the value at the third comparison. $oo% below: ;.,ompare ;GY vs ;GL : &ove to right node <.,ompare ;GY vs ;G= : &ove to right node L.,ompare ;GY vs ;GY : &atched" return the record f numbers of records are less" you cannot see a different one. /ow apply this techni1ue with a Dahoo email user accounts stored in a table called say Dahoo$ogin. $et us assume there are LL million users around the world that have Dahoo email id and that is stored in the Dahoo$ogin. Bhen a user logs in by giving the user name and password" the comparison re1uired is ; to <C" with the binary tree that is clustered inde*. $oo% at the above picture and guess yourself how fast you will reach into the level <C. Bithout ,lustered inde*" the comparison re1uired is ; to LL millions. #he above e*planation is for easy understanding. /ow a days SV$ server is using the @6#ree techni1ues to represent the clustered inde*. Not the usage of ,lustered inde*Q $et us move to /on6,lustered inde*. /on ,lustered nde* A non6clustered inde* is useful for columns that have some repeated values. Say for

e*ample" Account#ype column of a ban% database may have ;G million rows. @ut" the distinct values of account type may be ;G6;C. A clustered inde* is automatically created when we create the primary %ey for the table. Be need to ta%e care of the creation of the non6clustered inde*. Follow the steps below to create a /on6clustered inde* on our table Student based on the column class. ;.After e*panding the Student table" right clic% on the nde*es. And clic% on the /ew nde*. <.From the displayed dialog" type the inde* name as shown below and then clic% on the Add button to select the column's) that participate in the inde*. &a%e sure the nde* type is /on6,lustered. L. n the select column dialog" place a chec% mar% for the column class. #his tells that we need a non6clustered inde* for the column Student.,lass. Dou can also combine more than one column to create the nde*. Once the column is selected" clic% on the O? button. Dou will return the dialog shown above with the selected column mar%ed in blue. Our inde* has only one column. f you selected more than one column" using the&oveEp and &ove0own button" you can change order of the inde*ed columns. Bhen you are using the combination of columns" always use the highly repeated column first and more uni1ue columns down in the list. For e*ample" let use assume the correct order for creating the /on6clustered inde* is: ,lass"0ateOf@irth" PlaceOf@irth. .o, %oes a :onB8lustere( "n(e- Wor+?
A table can have more than one 5on&1lustered index. !ut, it should have only one clustered index that wor$s based on the !inary tree concept. 5on&1lustered column always depends on the 1lustered column on the database. This can be easily explained with the concept of a boo$ and its index page at the end. /et us assume that you are going to a boo$shop and found a big %FGG pages of 1H boo$ that says all about 1H. 'hen you glanced at the boo$, it has all beautiful color pages and shiny papers. !ut, that is not only the eligibility for a good boo$ rightI ne you are impressed, you want to see your favorite topic of Begular ,xpressions and how it is explained in the boo$. 'hat will you doI I "ust peeped at you from behind and recorded what you did as below: %.#ou went to the Index page <it has total )F pages=. It is already sorted and hence you easily pic$ed up Begular ,xpression that comes on page 5umber %J. ).5ext, you noted down the number displayed next to it which is 8GJ, K%L, %)GG&%))G. 7.#our first target is 0age 8GJ. #ou opened a page in the middle, the page is greater than FGG. 8.Then you moved to a somewhat lower page. !ut it still reads 7%G. F.Then you moved to a higher page. #ou are very luc$y you exactly got page 8GJ. M#es man you got it. therwise I need to write more. NIO L.That>s all, you started exploring what is written about Begular expression on that page, $eeping in mind that you need to find page K%L also. In the above scenario, the Index page is 5on&1lustered index and the page numbers are clustered index arranged in a binary tree. +ee how you came to the page 8GJ very :uic$ly. #our mind actually traversed the binary tree way left and right to reach the page 8GJ :uic$ly. 2ere, the class column with distinct values %,),7..%) will store the clustered index columns value along with it. +ay for example; /et us ta$e only class value of %. The Index goes li$e this:
e

%* %..& %.;& %.>

M.,lic% on the nde* folder on the right side and you will see the non6clustered inde* based on the column class is created for you.

What is <$!4 '<nline !ransaction 4rocessin)(? $n !5T& 3 online transaction processing systems relational database design use the discipline of data modeling and generally follow the Codd rules of data normali2ation in order to ensure absolute data integrity. 9sing these rules complex information is bro"en down into its most simple structures :a table; where all of the individual atomic level elements relate to each other and satisfy the normali2ation rules. What=s the difference *et"een a primary #ey and a uni8ue #ey? )oth primary "ey and uni#ue "ey enforces uni#ueness of the column on which they are defined. )ut by default primary "ey creates a clustered index on the column, where are uni#ue creates a nonclustered index by default. 4nother ma%or difference is that, primary "ey doesn't allow *955s, but uni#ue "ey allows one *955 only. What is difference *et"een D $ ! and !19NC+! commands?

0elete command removes the rows from a table based on the condition that we provide with a W8 < clause. Truncate will actually remove all the rows from a table and there will be no data in the table after we run the truncate command.

;.

<.

!19NC+! , -. T<9*C4T is faster and uses fewer system and transaction log resources than 0 5 T . 7. T<9*C4T removes the data by deallocating the data pages used to store the table's data, and only the page deallocations are recorded in the transaction log. ?. T<9*C4T removes all rows from a table, but the table structure, its columns, constraints, indexes and so on, remains. The counter used by an identity for new rows is reset to the seed for the column. =. +ou cannot use T<9*C4T T4)5 on a table referenced by a .!< $1* I + constraint. )ecause T<9*C4T T4)5 is not logged, it cannot activate a trigger. E. T<9*C4T cannot be rolled bac". C. T<9*C4T is 005 Command. J. T<9*C4T <esets identity of the table D $ ! , -. 0 5 T removes rows one at a time and records an entry in the transaction log for each deleted row. 7. $f you want to retain the identity counter, use 0 5 T instead. $f you want to remove table definition and its data, use the 0<!& T4)5 statement. ?. 0 5 T Can be used with or without a W8 < clause =. 0 5 T 4ctivates Triggers. E. 0 5 T can be rolled bac". C. 0 5 T is 0M5 Command. J. 0 5 T does not reset identity of the table.

*ote, 0 5 T and T<9*C4T both can be rolled bac" when surrounded by T<4*S4CT$!* if the current session is not closed. $f T<9*C4T is written in Guery ditor surrounded by T<4*S4CT$!* and if session is closed, it can not be rolled bac" but 0 5 T can be rolled bac". When is the use of 94D+! >S!+!IS!ICS command? This command is basically used when a large processing of data has occurred. $f a large amount of deletions any modification or )ul" Copy into the tables has occurred, it has to update the indexes to ta"e these changes into account. 9&04T KST4T$ST$CS updates the indexes on these tables accordingly. What are the properties and different !ypes of Su*-7ueries? ?. 4roperties of Su*-7uery -. 4 sub3#uery must be enclosed in the parenthesis. 7. 4 sub3#uery must be put in the right hand of the comparison operator, and ?. 4 sub3#uery cannot contain an !<0 <3)+ clause. =. 4 #uery can contain more than one sub3#uery. 3. !ypes of Su*-7uery -. Single3row sub3#uery, where the sub3#uery returns only one row. 7. Multiple3row sub3#uery, where the sub3#uery returns multiple rows,. and

?. Multiple column sub3#uery, where the sub3#uery returns multiple columns What is S7$ 4rofiler? SG5 &rofiler is a graphical tool that allows system administrators to monitor events in an instance of Microsoft SG5 Server. +ou can capture and save data about each event to a file or SG5 Server table to analy2e later. .or example, you can monitor a production environment to see which stored procedures are hampering performances by executing too slowly. 9se SG5 &rofiler to monitor only the events in which you are interested. $f traces are becoming too large, you can filter them based on the information you want, so that only a subset of the event data is collected. Monitoring too many events adds overhead to the server and the monitoring process and can cause the trace file or trace table to grow very large, especially when the monitoring process ta"es place over a long period of time. What is 9NI79 @ A constraint?

4 9*$G9 constraint enforces the uni#ueness of the values in a set of columns, so no duplicate values are entered. The uni#ue "ey constraints are used to enforce entity integrity as the primary "ey constraints. What is 41IM+1A @ A? 4 &<$M4<+ I + constraint is a uni#ue identifier for a row within a database table. very table should have a primary "ey constraint to uni#uely identify each row and only one primary "ey constraint can be created for each table. The primary "ey constraints are used to enforce entity integrity. What is F<1 IGN @ A? 4 .!< $1* I + constraint prevents any actions that would destroy lin"s between tables with the corresponding data values. 4 foreign "ey in one table points to a primary "ey in another table. .oreign "eys prevent actions that would leave rows with foreign "ey values when there are no primary "eys with that value. The foreign "ey constraints are used to enforce referential integrity. What is C, C@ Constraint? 4 C8 CI constraint is used to limit the values that can be placed in a column. The chec" constraints are used to enforce domain integrity. ,o" to )et BB 11<1 and BB1<WC<9N! at the same time? $f LL<owcount is chec"ed after rror chec"ing statement then it will have 6 as the value of LL<ecordcount as it would have been reset. 4nd if LL<ecordcount is chec"ed before the error3chec"ing statement then LL rror would get reset. To get LLerror and LLrowcount at the same time do both in same statement and store them in local variable. SELECT @RC = @@ROWCOUNT, @ER = @@ERROR What is a Scheduled 0o*s or What is a Scheduled !as#s? Scheduled tas"s let user automate processes that run on regular or predictable cycles. 9ser can schedule administrative tas"s, such as cube processing, to run during times of slow business activity. 9ser can also determine the order in which tas"s run by creating %ob steps within a SG5 Server 4gent %ob. .g. bac" up database, 9pdate Stats of Tables. >ob steps give user control over flow of execution. $f one %ob fails, user can configure SG5 Server 4gent to continue to run the remaining tas"s or to stop execution. What are the ad.anta)es of usin) Stored 4rocedures? -. Stored procedure can reduced networ" traffic and latency, boosting application performance. 7. Stored procedure execution plans can be reused, staying cached in SG5 Server's memory, reducing server overhead. ?. Stored procedures help promote code reuse. =. Stored procedures can encapsulate logic. +ou can change stored procedure code without affecting clients. E. Stored procedures provide better security to your data.

Stored Procedures

Stored Procedures are pre6compile objects which are compiled for first time and its compiled format is saved which e*ecutes 'compiled code) whenever it is called. @ut Function is compiled and e*ecuted every time when it is called. For more about stored procedure and function refer the articles 0ifferent types of Stored Procedure and 0ifferent types of Function. @asic 0ifference ;.Function must return a value but in Stored Procedure it is optional' Procedure can return -ero or n values). <.Functions can have only input parameters for it whereas Procedures can have input!output parameters . L.Function ta%es one input parameter it is mandatory but Stored Procedure may ta%e o to n input parameters.. M.Functions can be called from Procedure whereas Procedures cannot be called from Function. Advance 0ifference ;.Procedure allows SE$E,# as well as 0&$' /SE.#!EP0A#E!0E$E#E) statement in it whereas Function allows only SE$E,# statement in it. <.Procedures can not be utili-ed in a SE$E,# statement whereas Function can be embedded in a SE$E,# statement. L.Stored Procedures cannot be used in the SV$ statements anywhere in the BFE.E!FA2 /N!SE$E,# section whereas Function can be. M.Functions that return tables can be treated as another rowset. #his can be used in RO /s with other tables. C. nline Function can be though of as views that ta%e parameters and can be used in RO /s and other .owset operations. =.E*ception can be handled by try6catch bloc% in a Procedure whereas try6catch bloc% cannot be used in a Function. Y.Be can go for #ransaction &anagement in Procedure whereas we canKt go in Function.
/. ")C*A+) /0ut-ut1alue 1A+C#A+23445 )6)C sp)'ample 7Code-ro8ect7, /0ut-ut1alue 0,T-,T -+!NT /0ut-ut1alue ./ C5BA#B 259CB)L5B +dbo,.+spB@a"ple, Mpara"eter% JA5CGA5(%..) &Mpara"eter' JA5CGA5('..) 9L#2L# A 3B41N )BCLA5B Mpara"eter: JA5CGA5(%..) B# Mpara"eter: - C Eour develop"ent resources.C 17 Mpara"eter% 1 N9# NLLL AN) LBN(Mpara"eter%) I % BLBC# Mpara"eter' - C#he C ( Mpara"eter% ( Mpara"eter: BL B 5B#L5N BLBC# Mpara"eter' - CCode2roNect is coolOC

BN) 49

Statement
)NS+R0 )N0G table_name (column1?column2?column3?!!! $.#K+S (value1?value2?value3?!!! ;

K:*.0+ table_name S+0 column1=value1?column2=value2?!!! "H+R+ some_column=some_value; *+#+0+ CRGM table_name "H+R+ some_column=some_value; S+#+C0 Grders!Grder)*? Customers!CustomerName? Grders!Grder*ate CRGM Grders )NN+R RG)N Customers GN Grders!Customer)*=Customers!Customer)*; S+#+C0 Customers!CustomerName? Grders!Grder)* CRGM Customers )NN+R RG)N Grders GN Customers!Customer)*=Grders!Customer)* GR*+R &N Customers!CustomerName; S+#+C0 Customers!CustomerName? Grders!Grder)* CRGM Customers #+C0 RG)N Grders GN Customers!Customer)*=Grders!Customer)* GR*+R &N Customers!CustomerName; S+#+C0 Grders!Grder)*? +mployees!CirstName CRGM Grders R)(H0 RG)N +mployees GN Grders!+mployee)*=+mployees!+mployee)* GR*+R &N Grders!Grder)*;

SG5 .955 !9T < >!$* xample


The following SG5 statement selects all customers, and all orders,

S+#+C0 Customers!CustomerName? Grders!Grder)* CRGM Customers CK## GK0+R RG)N Grders GN Customers!Customer)*=Grders!Customer)* GR*+R &N Customers!CustomerName;

Bhat is the need of BPF when we had windows formsQ


A & Anywhere execution < 'indows or 'eb= ! & !indings < less coding= 1 & 1ommon loo$ and feel < resource and styles=

D & Declarative programming <-A./= , & ,xpression blend animation < Animation ease= F & Fast execution < 2ardware acceleration= E & Eraphic hardware independent < resolution independent=

Bhat is \A&$ in BPF and why do we need itQ


-A./ is a -./ file which represents your '0F 3I. The whole point of creating the 3I representation in -./ was write once and run it anywhere. +o the same -A./ 3I can be rendered as windows application with '0F and the same 3I can be displayed on the browser using '0F browser or +ilverlight application.

Bhat is *mlns in \A&$ fileQ Pxmlns@ stands for -./ namespaces. It helps us to avoid name conflicts and confusion in -./
documents. For example consider the below two -./ which have table elements, one table is a 2T./ table and the other represents a restaurant table. 5ow if both these elements come in a single -./ document there would name conflicts and confusion.
HtableI HtrIHtdI5o$%H8tdIH8trI HtrIHtdI5o$'H8tdIH8trI H8tableI ------------------------------HtableI HclothIredH8clothI HserveI#eaH8serveI H8tableI

+o to avoid the same we can use -./ namespaces. #ou can see in the below -./ we have :ualified the 2T./ table with ?@ and the restaurant table element :ualified with ?@.

(h:table *mlns:h:Jhttp:!!www.wL.org!#.!htmlM!J+
HtrIHtdI5o$%H8tdIH8trI HtrIHtdI5o$'H8tdIH8trI H8h*tableI -------------------------------Hr*table @"lns*h-"http*88$$$.Kuestpond.co"8restaurant8table8de0"I HclothIredH8clothI HserveI#eaH8serveI H8r*tableI

Bhat is the difference between *mlns and *mlns:* in BPF Q


!othe namespaces helps to define C resolved -A./ 3I elements. The first namespace is the default namespace and helps to resolve overall '0F elements.

*mlns:Jhttp:!!schemas.microsoft.com!winf*!<GG=!*aml!presentationJ
The second namespace is prefixed by ?x:@ and helps to resolve -A./ language definition.

*mlns:*:Jhttp:!!schemas.microsoft.com!winf*!<GG=!*amlJ

For instance for the below -A./ snippet , we have two things one is the ?+tac$0anel@ and the other is

?x:name@. ?+tac$0anel@ is resolved by the default namespace and the ?x:name@ is resolved by using ?xmlns:x@ namespace.
H tac62anel @*Na"e-""! tac6" 8I

Bhat are the different %inds of controls in BPFQ


'0F controls can be categori9ed in to four categories:&

1ontrol: 6 #his is the basic control with which you will wor% most of time. For e*ample te*tbo*" buttons etc. /ow controls which are standalone control li%e button " te*t bo* " labels etc are termed as content control. /ow there are other controls which can hold other controls" for instance itemscontrols. temscontrol can have multiple te*tbo* controls" label controls etc. Shape: 6 #hese controls help us to create simple graphic controls li%e Ellipse" line" rectangle etc. Panel: 6 #hese controls help to align and position the controls. For instance grid helps us to align in a table manner" stac% panel helps for hori-ontal and vertical alignment. ,ontent presenter: 6 #his control helps to place any \A&$ content inside it. Esed when we want to add dynamic controls on a BPF screen. All the above four types of BPF controls finally inherit from the framewor%element class of BPF. ,an you e*plain the complete BPF object hierarchyQ Object: 6 As BPF is created using ./E# so the first class from which BPF E classes inherits is the ./E# object class. 0ispatcher: 6 #his class ensures that all BPF E objects can be accessed directly only by the thread who own him. Other threads who do not own him have to go via the dispatcher object. 0ependency: 6 BPF E elements are represented by using \A&$ which is \&$ format. At any given moment of time a BPF element is surrounded by other BPF elements and the surrounded elements can influence this element and this is possible because of this dependency class. For e*ample if a te*tbo* surrounded by a panel" its very much possible that the panel bac%ground color can be inherited by the te*tbo*. 2isual: 6 #his is the class which helps BPF E to have their visual representation. E Element: 6 #his class helps to implement features li%e events" input" layouting etc. Framewor% element: 6 #his class supports for templating " styles " binding " resources etc. And finally all BPF controls te*tbo* " button " grids and whatever you can thin% about from the BPF tool bo* inherits from the framewor% element class. 0oes that mean BPF has replaced 0irect\Q /o" BPF does not replace 0irect\. 0irect\ will still be still needed to ma%e cutting edge games. #he video performance of direct\ is still many times higher than BPF AP . So when it comes to game development the preference will be always 0irect\ and not BPF. BPF is not an optimum solution to ma%e games" oh yes you can ma%e a # , #A, #OE game but not high action animation games. One point to remember BPF is a replacement for windows form and not direct\. So is \A&$ meant only for BPF Q /o"\A&$ is not meant only for BPF.\A&$ is a \&$6based language and it had various variants. BPF \A&$ is used to describe BPF content" such as BPF objects" controls and documents. n BPF \A&$ we also have \PS \A&$ which defines an \&$ representation of electronic documents. Silverlight \A&$ is a subset of BPF \A&$ meant for Silverlight applications. Silverlight is a cross6platform browser plug6in which helps us to create rich web content with <6dimensional

graphics" animation" and audio and video. BBF \A&$ helps us to describe Bindows Bor%flow Foundation content. BBF engine then uses this \A&$ and invo%es wor%flow accordingly. ,an you e*plain the overall architecture of BPFQ Above figure shows the overall architecture of BPF. t has three major sections presentation core" presentation framewor% and milcore. n the same diagram we have shown how other section li%e direct and operating system interact with the system. So letAs go section by section to understand how every section wor%s. EserL<:6 t decides which goes where on the screen. 0irect\: 6 As said previously BPF uses direct\ internally. 0irect\ tal%s with drivers and renders the content. &ilcore: 6 &il stands for media integration library. #his section is a unmanaged code because it acts li%e a bridge between BPF managed and 0irect\ ! EserL< unmanaged AP . Presentation core :6 #his is a low level AP e*posed by BPF providing features for <0 " L0 " geometry etc. Presentation framewor%:6 #his section has high level features li%e application controls " layouts . ,ontent etc which helps you to build up your application. Bhat is App.*aml in BPF projectQ App.*aml is the start up file or a boot strapper file which triggers your first \A&$ page from your BPF project. Bhat are various ways of doing alignment in BPFQ #here are five ways of doing alignment in BPF:6 Nrid:6 n Nrid alignment we divide the screen in to static rows and columns li%e F#&$ tables and position elements in those rows and column area.
H4ridI H4rid.Colu"n)e0initionsI HColu"n)e0inition 8I HColu"n)e0inition 8I H84rid.Colu"n)e0initionsI H4rid.5o$)e0initionsI H5o$)e0inition 8I H5o$)e0inition 8I H84rid.5o$)e0initionsI HLabel 4rid.Colu"n-"." 4rid.5o$-"." 3ac6ground-"5ed"I%st colu"n %st ro$ H8LabelI HLabel 4rid.Colu"n-"%" 4rid.5o$-"." 3ac6ground-"Light4reen"I'nd Colu"n 'nd ro$H8LabelI HLabel 4rid.Colu"n-"." 4rid.5o$-"%" 3ac6ground-"5ed"I%st colu"n 'nd ro$H8LabelI HLabel 4rid.Colu"n-"%" 4rid.5o$-"%" 3ac6ground-"Light4reen"I'nd Colu"n 'nd ro$H8LabelI H84ridI

Stack panel :) Arranges control in vertical or hori9ontal format.


H tac62anel 9rientation-"Jertical"I HLabel 3ac6ground-"5ed"I5ed H8LabelI HLabel 3ac6ground-"Light4reen"I4reen H8LabelI HLabel 3ac6ground-"Light3lue"I3lue H8LabelI HLabel 3ac6ground-"Eello$"IEello$ H8LabelI H8 tac62anelI

&rapPanel :)Aligns elements in a line until the border is hit , then wraps in to the next line.

HWrap2anel 9rientation-"GoriAontal"I HLabel Width-"%'>" 3ac6ground-"5ed"I5ed %H8LabelI HLabel Width-"%.." 3ac6ground-"Light4reen"I4reen %H8LabelI HLabel Width-"%'>" 3ac6ground-"Light3lue"I3lue %H8LabelI HLabel Width-">." 3ac6ground-"Eello$"IEello$ %H8LabelI HLabel Width-"%>." 3ac6ground-"9range"I9range %H8LabelI HLabel Width-"%.." 3ac6ground-"5ed"I5ed 'H8LabelI HLabel Width-"%>." 3ac6ground-"Light4reen"I4reen 'H8LabelI HLabel Width-"P>" 3ac6ground-"Light3lue"I3lue 'H8LabelIH8Wrap2anelI

Doc$ 0anel: & Aligns controls in five different regions: top, bottom, left, right and center.

(0oc%Panel+
HLabel )oc62anel.)oc6-"#op" Geight-"%.." 3ac6ground-"5ed"I#op %H8LabelI HLabel )oc62anel.)oc6-"Le0t" 3ac6ground-"Light4reen"ILe0tH8LabelI HLabel )oc62anel.)oc6-"5ight" 3ac6ground-"LightC!an"I5ightH8LabelI HLabel )oc62anel.)oc6-"3otto"" 3ac6ground-"Light3lue"I3otto"H8LabelI H#e@t3loc6 JerticalAlign"ent-"Center" GoriAontalAlign"ent-"Center"I )e"o o0 )oc6 panelH8#e@t3loc6I H8)oc62anelI

'hat are resources in '0FI


Besources are ob"ects referred in '0F -A./. In 1H code when we create an ob"ect we do the following three steps :&
1ollapse D ,opy ,ode

using Custo"erNa"e pace; 88 i"port the na"espace. Custo"er obN - ne$ Custo"er(); 88 Create obNect o0 the class #e@tbo@%.te@t - obN.Custo"erCode; 88 3ind the obNect $ith L1 ele"ents

+o even in '0F -A./ to define resources which are nothing but ob"ects we need to the above 7 steps :& Import namespace where the class resides: & To define namespace we need to use the ?xmlns@ attribute as shown in the below -A./ code.
1ollapse D ,opy ,ode

HWindo$ @*Class-"LearnWp05esources.MainWindo$" @"lns-"http*88sche"as."icroso0t.co"8$in0@8'..Q8@a"l8presentation" @"lns*@-"http*88sche"as."icroso0t.co"8$in0@8'..Q8@a"l" @"lns*custns-"clr<na"espace*LearnWp05esources" #itle-"MainWindo$" Geight-":>." Width-">'>"I

1reate ob"ect of the class :& To create an ob"ect of the class in -A./ we need to create a resource by using the resource tag as the below code. #ou can the ob"ect name is Acustob"@.
1ollapse D ,opy ,ode

HWindo$.5esourcesI Hcustns*Custo"er @*?e!-"custobN"8I H8Windo$.5esourcesI

The above code you can map to something li$e this in 1H


1ollapse D ,opy ,ode

Custo"er custobN - ne$ Custo"er();

!ind the ob"ect with 3I ob"ects :& nce the ob"ect is created we can then bind them using bindings li$e one way , two way as explained in ?,xplain one way, two way, one time and one way to sourceI@ :uestion explained above.
1ollapse D ,opy ,ode

H#e@t3o@ #e@t-"{3inding Custo"erCode& Mode-#$oWa!&

ource-{ tatic5esource custobN}}" 8I

E*plain the difference between static and dynamicresourceQ


Besources can be referred statically or dynamically. +tatic referred resources evaluate the resource only once and after that if the resources change those changes are not reflected in the binding. 'hile dynamic referred resources are evaluated every time the resource is needed. 1onsider the below ?+olid1olor!rush@ resource which is set to ?/ight!lue@ color.
1ollapse D ,opy ,ode

HWindo$.5esourcesI H olidColor3rush Color-"Light3lue" @*?e!-"button3ac6ground" 8I H8Windo$.5esourcesI

The above resource is binded with the below two textboxes statically and dynamically respectively.
1ollapse D ,opy ,ode

H#e@t3o@ 3ac6ground-"{)!na"ic5esource button3ac6ground}" 8I Hte@tbo@ bac6ground-"{ tatic5esource button3ac6ground}"I

5ow if we modify the resource , you see the first text box changes the bac$ground and the other textbox color stays as it is.
1ollapse D ,opy ,ode

private void 3uttonRClic6(obNect sender& 5outedBventArgs e) { 5esources+"button3ac6ground", - 3rushes.3lac6; }

!elow is the output of the same.

Bhen should we use static resource over dynamic resource Q


Dynamic resources reduce application performance because they are evaluated every time the resource is needed. +o the best practice is use +tatic resource until there is a specific reason to use dynamic resource. If you want resource to be evaluated again and again then only use dynamic resource.

E*plain the need of binding and commandsQ


'0F !inding>s helps to send C receive data between '0F ob"ects while command helps to send and receive actions.The ob"ect that emits data or action is termed as source and the ob"ect who wants to receive data or action is termed as target.

E*plain one way" two way" one time and one way to sourceQ
All the above 8 things define how data will flow between target and source ob"ects when '0F binding is applied.

Two way: & Data can flow from both source to target and from target to source. ne way: & Data flows only from source to target. ne way to source: & Data flows only from target to source. ne time: & Data flows only for the first time from source to target and after that no communication happens. !elow is an easy tabular representation to memori9e the same.
ne way to source

Data flo. 0indin%s Two way ne way to source ne way ne time #ar%et to Source #es #es 5o 5o Source tar%et #es 5o #es For first #es

,an you e*plain BPF command with an e*ampleQ


'hen end users interact with application they send actions li$e button clic$, right clic$ , control P c, control P v etc. A command class in '0F wraps these end user actions in to a class so that they can be reused again and again. '0F 1ommand class idea is an implementation of command pattern from gang of four design pattern. To create a command class we need to implement the ?I1ommand@ interface. For example below is a simple command class which increments a counter class by calling ?Increment@ method.
1ollapse D ,opy ,ode

public class 1ncre"entCounter * {

!ste".Windo$s.1nput.1Co""and

private clsCounter obN; public 1ncre"entCounter(clsCounter o) { obN - o; } public bool CanB@ecute(obNect para"eter) { return true; } public event BventGandler CanB@ecuteChanged; public void B@ecute(obNect para"eter) { obN.1ncre"ent(); } }

The command class needs two implement two methods as shown in the above code:&

'hat to ,xecute <,xecute= Q 1ommand class is all about wrapping actions of end users so that we can reuse them. At the end of the day Action invo$es methods. .ean for instance a ?btnmathsRclic$@ action will invo$e ?Add@ method of a class. The first thing we need to specify in the command class is which method you want to execute. In this case we want to call the ?Increment@ method of ?cls1ounter@ class. 'hen to execute <1an,xecute= Q The second thing we need to specify is when the command can execute, means validations. This validation logic is specified in the ?1an,xecute@ function. If the validation returns true then ?,xecute@ fires or else the action has no effect. #ou can see the code of ?1an,xecute@ and ?,xecute@ in the above code snippet. nce you have created the ?1ommand@ class you can bind this with the button using the ?1ommand@ property as shown in the below -A./ code.@1ounter b"@ is a resource ob"ect.
1ollapse D ,opy ,ode

H3utton Co""and-"{3inding 1ncre"entClic6&

ource-{ tatic5esource CounterobN}}"8I

+o now that the action is wrapped in to command we do not need to write method invocation code again and again in behind code, we "ust need to bind the command ob"ect with the '0F 3I controls wherever necessary.

Fow does PEpdateSource#riggerX affect bindingsQ


P3pdate+ourceTrigger@ decides when the data should get updated between '0F ob"ects that are
binded. In other word should data get updated in lost focus event, in data change event etc. There are four modes by which ?3pdate+ourceTrigger@ can be defined:& Default: & If it>s a text property then data is updated during lost focus and for normal properties data updates in property change event. 0roperty1hanged: & In this setting data is updated as soon as the value is changed. /ostFocus: & In this setting data is updated as soon as lost focus event occurs. ,xplicit: & In this setting the data is updated manually. In other words to update data between two '0F ob"ect you need to call the below code.
1ollapse D ,opy ,ode

3indingB@pression binding -t@t%.4et3indingB@pression(#e@t3o@.#e@t2ropert!); binding.Lpdate ource();

To set ?3pdate+ourceTrigger@ we need to use the ?3pdate+ourceTrigger@ value which can be found in the bindings properties as shown in the below figure.

E*plain the need of P /otifyProperty,hangedX interfaceQ


'hen we bind two '0F ob"ects the target data is updated depending on the ?3pdate+ourceTrigger@ events. 0lease refer the previous :uestion for ?3pdate+ourceTrigger@ basics. The ?3pdate+ourceTrigger@ has events li$e lostfocus , property change etc. In other words when lostfocus or property change event happen on the target it ma$es a 03// to the source to get the latest data. +o it>s very much possible that the '0F source data has changed and because the '0F target ?3pdate+ourceTrigger@ event did not fire he did not ma$e a pull and the data of the source is not in synch with the target. This is where ?I5otify0roperty1hanged@ interface comes to use. !elow is a simple ?cls1ounter@ class which has a ?1ounter@ property and this property is incremented by ?Increment@ method.

5ow if we bind '0F label or textbox to the ?1ounter@ property and call the ?Increment@ method the new ?1ounter@ value will not be propagated to the target. !ecause invo$ing a method does not trigger any ?3pdate+ourceTrigger@ event. +o after calling the ?Increment@ method the ?1ounter@ value of the source and the target are out of synch. +o create a push event from the source you need to first implement ?I5otify0roperty1hanged@ interface as shown in the below figure. 5ow when someone calls the ?Increment@ method you can raise an event saying that the ?1ounter@ property has changed by calling ?0roperty1hanged@ function as shown in the below code. In simple words the source sends a notification to the target '0F ob"ect that data has changed in the source and he should refresh himself with the fresh data.
1ollapse D ,opy ,ode

2ropert!Changed(this& ne$ 2ropert!ChangedBventArgs("Counter"));

!elow is full ?cls1ounter@ class code with ?I5otify0roperty1hanged@ implemented.


1ollapse D ,opy ,ode

public class clsCounter * 1Noti0!2ropert!Changed { private int RCounter-.; public int Counter { get { return RCounter; } } public void 1ncre"ent() { RCounter((; 2ropert!Changed(this& ne$ 2ropert!ChangedBventArgs("Counter")); }

public event 2ropert!ChangedBventGandler 2ropert!Changed; }

Bhat are value converters in BPFQ


!inding is one of the big features in '0F which helps us to facilitate data flow between '0F 3I and b"ect. !ut when data flows from source to 3I or vice&versa using these bindings we need to convert data from one format to other format. For instance let>s say we have a ?0erson@ ob"ect with a married string property. /et>s assume that this ?married@ property is binded with a chec$ box. +o if the text is ?.arried@ it should return true so that the option chec$ box loo$>s chec$ed. If the text is ?3nmarried@ it should return false so that the option chec$ box loo$s unchec$ed. In simple words we need to do data transformation. This is possible by using ?*alue 1onverters@. In order to implement value converters we need to inherit from ?I*alue1onverted@ interface and implement two methods ?1onvert@ and ?1onvert!ac$@.

1ollapse D ,opy ,ode

public class MaritalConverter * 1JalueConverter { public obNect Convert(obNect value& #!pe target#!pe& obNect para"eter& !ste".4lobaliAation.Culture1n0o culture) { string "arried - (string)value; i0 ("arried -- "Married") { return true; } else { return 0alse; } } public obNect Convert3ac6(obNect value& #!pe target#!pe& obNect para"eter& !ste".4lobaliAation.Culture1n0o culture) { bool "arried - (bool)value; i0 ("arried) { return "Married"; } else { return "LnMarried"; } } }

#ou can see in the ?1onvert@ function we have written logic to transform ?.arried@ to true and from ?3nmarried@ to false. In the ?1onvertbac$@ function we have implemented the reverse logic.

E*plain multi binding and multivalue converters in BPFQ


P.ulti!inding@ helps you bind multiple sources to a target while multi&converters acts li$e bridge if the
source and targets have different data formats or need some conversion. For example let>s say you have two textboxes which has ?First5ame@ and ?/ast5ame@. #ou want that as soon as users type on these two textboxes, the other text box should get updated with ?First5ame/ast5ame@ < As shown in the below figure=. Also vice versa if we type in the third text box ?First5ame/ast5ame@ it should display ?First5ame@ and ?/ast5ame> in the other two textboxes respectively. +o the first thing is to create a multivalue converter class which will "oin ?First5ame@ and ?/ast5ame@ in to source and split ?First5ame/ast5ame@ bac$ to target. For the same we need to implement ?I.ulti*alue1onverter@ and implement ?1onvert@ and ?1onvert!ac$@ methods.

?1onvert@ helps to do conversion from ?Target@ to ?+ource@ and ?1onvert!ac$@ helps to convert from ?+ource@ to ?Target@.
1ollapse D ,opy ,ode

public class Na"eMultiConverter * 1MultiJalueConverter { public obNect Convert(obNect+, values& #!pe target#!pe& obNect para"eter& !ste".4lobaliAation.Culture1n0o culture) { // Conversion logic from Target to %ource } } public obNect+, Convert3ac6(obNect value& #!pe+, target#!pes& obNect para"eter& !ste".4lobaliAation.Culture1n0o culture) { // Conversion logic from %ource to Target$ } }

!elow is the ?1onvert@ < Target to +ource= implementation where we get the ?textbox@ value in a array and we have concatenated the array values and returned the same in a single string. This single string will be displayed in the third textbox.
1ollapse D ,opy ,ode

public obNect Convert(obNect+, values& #!pe target#!pe& obNect para"eter& !ste".4lobaliAation.Culture1n0o culture) { string @ - ""; 0oreach (obNect ! in values) { @ - @ ( " " ( !.#o tring(); } return @; }

P1onvert!ac$@ helps to implement conversion logic from ?+ource@ to ?Target@. +o when someone types
?+hiv Noirala@ in the third text box we would li$e to split ?+hiv@ in one string and ?Noirala@ in other string. +o you can see in the below code we have used the ?+plit@ function to create a string array. +o the first array index < arrayMGO= will go to the first textbox and the second array index <arrayM%O= will go to the second text box.
1ollapse D ,opy ,ode

public obNect+, Convert3ac6(obNect value& #!pe+, target#!pes& obNect para"eter& !ste".4lobaliAation.Culture1n0o culture) { string str - (string)value; string+, val - str. plit(C C);

return val;

5ow once we are done with the converter next thing is to apply multi&binding. !elow is the -A./ code where we have the three text boxes ?txtFirst5ame@ , ?txt/ast5ame@ and ?txtFirstAnd/ast@. #ou can see how the ?txtFirstAnd/ast@ textbox ?Text@ is binded using multibinding element which binds to ?txtFirst5ame@ and ?txt/ast5ame@ textbox . +o now if you ma$e changes to multiple target the single source gets updated and if you update the source multiple target gets updates.
1ollapse D ,opy ,ode

H#e@t3o@ @*Na"e-"t@t7irstNa"e" GoriAontalAlign"ent-"Le0t" Geight-"'Q" Margin-";'&QP&.&." #e@tWrapping-"Wrap" #e@t-"" JerticalAlign"ent-"#op" Width-"%>'"8I H#e@t3o@ @*Na"e-"t@tLastNa"e" GoriAontalAlign"ent-"Le0t" Geight-"'Q" Margin-";%&%:>&.&." #e@tWrapping-"Wrap" #e@t-"" JerticalAlign"ent-"#op" Width-"%>:"8I H#e@t3o@ @*Na"e-"t@t7irstAndLast" Na"e-"label%" Geight-"'S" GoriAontalAlign"ent-"Le0t" Margin-"':=&%.:&.&."

JerticalAlign"ent-"#op" Width-"%%P"I H#e@t3o@.#e@tI HMulti3inding Converter-"{ tatic5esource Na"eMultiConverter}"I H3inding Ble"entNa"e-"t@t7irstNa"e" 2ath-"#e@t" 8I H3inding Ble"entNa"e-"t@tLastNa"e" 2ath-"#e@t" 8I H8Multi3indingI H8#e@t3o@.#e@tI H8#e@t3o@I

E*plain BPF relative binding ! relative resourceQ


'hen we define bindings we need at least two elements target and source. !ut many times rather than defining binding between two elements we would li$e to define binding with reference to the current element i.e. B,/ATI*,/#. For instance let>s say we have a '0F border and we would li$e height and width of the broder to be same. +o for this scenario the target and source are the same, the '0F border itself. +o we can define the binding using ?Belative+ource@ as shown in the below code. #ou can see it uses ?+elf@ binding mode to bind the element to itself.
1ollapse D ,opy ,ode

H3order 3order3rush-"3lac6" 3order#hic6ness-"%" Geight-"%:=" Width-"{3inding Geight& 5elative ource-{5elative ource el0}}"8I

Bhat are the different ways of binding using relative sourceQ


There are four ways of binding relatively in '0F :&

+elf Ancestor 0reviousdata Templated parent

,an you e*plain self relative source binding in BPFQ


This relative binding helps to bind to one property of an element to the other property of the same element. For example in the below -A./ the border width is binded to height of the same border element.
1ollapse D ,opy ,ode

H3order 3order3rush-"3lac6" 3order#hic6ness-"%" Geight-"%:=" Width-"{3inding Geight& 5elative ource-{5elative ource el0}}"8I

E*plain Ancestor relative source binding in BPFQ


This relative binding helps to bind properties to the parent element properties. For example in the below -A./ code we have a textbox which has two border>s as a parent. ne border is having dar$ green and the other border is having dar$ red color as the border color. The dar$ green color border is the parent element followed by dar$ red and the text box the child element at the end of the hierarchy.
1ollapse D ,opy ,ode

H3order 3order3rush-")ar64reen"I H3order 3order3rush-")ar65edTI H#e@t3o@ 8I H83orderI H83orderI

!elow is how the '0F application loo$s li$e when it runs. 5ow we want the bac$ground color of the text box to be binded to one of the parent border colors. To achieve the same we can use ancestor relative binding. !elow are some important properties in Ancestor type binding we need to $now before we writing the binding code. Property Ancestor#ype Description &hich type of parent ele'ent is it$ (s it a border ele'ent / %rid ele'ent etc

An ele'ent can ha*e 'ultiple parents 1or e2a'ple in the abo*e 3AM, .e ha*e t.o parents one .ith red color and the other .ith %reen So this property specifies .hich le*el of parent ele'ent .e .ant to refer 0elo. Ancestor,e*el is the fi%ure .hich depicts the le*els #he red color border is le*el 1 and the %reen color border is le*el 4 So the nearest ele'ent beco'es the first le*el and so on 0indin% #his specifies .hich property .e .ant to bind to 1or the current e2a'ple .e .ant to bind to border5s brush color

+o the relative binding code with ancestor level % i.e. red loo$s as shown below. In case you are confused with any of the properties please refer to the previous table for more information.
1ollapse D ,opy ,ode

H#e@t3o@ 3ac6ground-"{3inding 3order3rush& 5elative ource-{5elative ource 7indAncestor& AncestorLevel-%& Ancestor#!pe-{@*#!pe 3order}}}"8I

+o now the complete -A./ with parent border element loo$s as shown in the below code.
1ollapse D ,opy ,ode

H3order 3order3rush-")ar64reen"IHO<< *evel 9: ;<order <order<rush=>"ark+ed?:;@99 *evel 3 9: ;Te't<o' removed=>A<inding <order<rush, +elative%ource=A+elative%ource BindAncestor, Ancestor*evel=3, AncestorType= A'CType <orderDDD>/: ;/<order: ;/<order:

5ow if you run the above -A./ code the textbox is binded with the bac$ ground color of the first border. If you change the ancestor level to ) textbox bac$ground color will change to green. 0reviousData
1ollapse D ,opy ,ode

H1te"sControl1te"s ource-"{3inding}" Margin-"%."I H1te"sControl.1te"#e"plateI H)ata#e"plateI H tac62anelI H#e@t3loc67ont iAe-"%;"7ontWeight-"bold" Margin-"'." #e@t-"{3inding Jalue}" re"oved-"AKua"I H8#e@t3loc6I H#e@t3loc67ont iAe-"%;"7ontWeight-"bold" Margin-"'." #e@t-"{3inding 5elative ource-{5elative ource2revious)ata}& 2ath-Jalue}" re"oved-"3lue"I H8#e@t3loc6I H8 tac62anelI H8)ata#e"plateI H81te"sControl.1te"#e"plateI H81te"sControlI publicclass1te" * 1Noti0!2ropert!Changed { privatedouble Rvalue; publicdouble Jalue { get { return Rvalue; } set { Rvalue - value; 9n2ropert!Changed("Jalue"); } } Uregion1Noti0!2ropert!Changed Me"bers publicevent2ropert!ChangedBventGandler2ropert!Changed; Uendregion protectedvoid9n2ropert!Changed(string2ropert!Na"e)

{ i0 (null O- 2ropert!Changed) { 2ropert!Changed(this& ne$2ropert!ChangedBventArgs(2ropert!Na"e)); } } } publicclass1te"s * 9bservableCollectionH1te"I { public 1te"s() { Add(ne$1te" { Jalue - S..': }); Add(ne$1te" { Jalue - %'Q.%P }); Add(ne$1te" { Jalue - %:..'% }); Add(ne$1te" { Jalue - %%>.'S }); Add(ne$1te" { Jalue - %:%.'% }); Add(ne$1te" { Jalue - %:>.'' }); Add(ne$1te" { Jalue - %'..'P }); Add(ne$1te" { Jalue - %%..'> }); Add(ne$1te" { Jalue - =..'. }); } }

E*plain the difference between visual and logical tree in BPF Q


'0F 3I is represented in -A./ which is a -./ format. In -./ elements are arranged in a hierarchal fashion. For example if you loo$ at the below -A./ <it has been downsi9ed for simplicity= we have a 'indow element, the window element has a Erid control and the grid control has a button inside it.
1ollapse D ,opy ,ode

HWindo$I H4ridI H3utton..I H84ridI H8Windo$I

+o if you visuali9e the above -A./ logically you can thin$ that the button control is a child element of the Erid and the grid is the child element of the 'indow. This relationship between the elements which loo$s logical loo$ing at the -A./ is termed as ?/ogical tree@. !ut now to display this /ogical tree on to your screen you need lot of visual elements. li$e border, text etc. +o when you add these visual elements to the logical tree that complete structure is termed as ?*isual Tree@. 0utting in simple words there is only tree in '0F but depending on how you view it these two trees are the outcome. If you use the '0F visuali9er the above -A./ tree loo$s something as shown in the below figure which is actually a complete visual tree.

In simple words whatever you see in your -A./ is a logical tree and to ma$e it display it uses the visual tree. !elow is an in detail figure which shows the logical and visual tree of the above -A./. /ogical tree is without the shades and with shades is the visual tree.

Bhy do we need to have these perspective of visual and logical tree in BPF Q
*isual tree and /ogical tree are important when you wor$ with '0F routed events.

E*plain routed events in BPFQ


Bouted events are those events which travel up or down the visual tree hierarchy. '0F events can be classified in to 7 types:& Direct events: & In this case event is raised at the source and handled at the source itself li$e ?.ouse,nter@ events. !ubbling events: & They travel up the visual tree hierarchy. For example ?.ouseDown@ is a bubbling event. Tunneling events: & These events travel down the visual tree hierarchy. ?0reviewNeyDown@ is a tunneling event.

Bhat are styles in BPFQ


'0F style helps to define loo$ and feel < color , fonts, alignments etc= from a central location so that we can have ease of maintenance.For more details on '0F styles please chec$ this lin$ out which also has simple sample BPF e*amples

Bhat are style triggersQ


.any times we would want a style property to execute under certain conditions. Trigger>s help you to define condition under which the style values will be set. For instance in the below -A./ code we have style trigger defined for button which set>s bac$ground color to ?Bed@ if there is focus on the button or else the bac$ ground color is set to ?A:ua@.
1ollapse D ,opy ,ode

H t!le @*?e!-""! t!le" #arget#!pe-"3utton"I H t!le.#riggersI H#rigger 2ropert!-"1s7ocused" Jalue-"#rue"I H etter 2ropert!-"3ac6ground" Jalue-"5ed"8I H8#riggerI H8 t!le.#riggersI H etter 2ropert!-"3ac6ground" Jalue-"AKua" 8I H8 t!leI

Bhat is &22&Q
.**. is an architecture pattern where we divide the pro"ect in to three logical layers and every layer has its own responsibility. !elow are the three logical layers with explanation what they do:& *iew: & This layer handles responsibility of ta$ing inputs from end user, positioning of controls, loo$ and feel, design, visuals, colors etc. .odel: & This layer represents your middle layer ob"ects li$e customer, supplier etc. It handles business logic and interaction with data access layer.

*iew .odel: & *iew model as it says *iew plus model represents your user interface. #ou can also visuali9e this class as the behind code. This class is the bridge between model and view. It handles connection logic , data transformation logic and action mapping between model and view. For example it will have following types of logics as shown below :& Beplicating and propagating data between views and models. 'hen someone enters data in to 3I or the model gets updated this layer will ensure that the propagation of data happens between these entities. 2andling data transformation from view to model and vice versa. For example you have a model which has gender property with data as ?.@ for male and ?F@ for female. !ut on the *iew or 3I you would li$e to display as a chec$ box with true and false. This transformation logic is written in the view model class. *iew model also map 3I actions to methods. For example you have ?btnRAdd@ clic$ event and when any one clic$s on this button you would li$e to invo$e ?1ustomer.Add<=@ method from the customer class. This connection code is again a part if view model.

Bhat are the benefits of &22&Q


!elow are the benefits of .**. pattern:& +eparation of concern: & As the pro"ect is divided in to layers, every layer handles its own responsibility. This leads to better maintenance because when we change one layer the other layer does not get affected. Increased 3I Beusability: & The whole point of .**. is to remove behind code i.e. -A./.1+ code. The problem with behind code is that it is tied up with a 3I technology for example A+0-.1+ code is tied up with the A+0 page class, -A./.1+ file is tied with '0F 3I technology and so on. +o we cannot use A+0-.1+ behind code with '0F -A./ 3I. !y moving the behind code to the view model class we can now use this with any 3I technology. Automated 3I 3nit testing: & *iew model class represents your 3I. The properties of the class represent 3I text boxes, combo boxes and the methods of the class represent action. 5ow as the 3I is represented by the view model class, we can do automated 3I testing using unit testing by creating the ob"ects of view model class and doing the necessary asserts.

Bhat is the importance of command and bindings in &22& patternQ


.**. in the most used architecture because of command and bindings facility provided by '0F. '0F .**. is incomplete without command and bindings. 1ommand and bindings helps you to connect view <'0F 3I= with view model class without writing lot of behind code. !inding connects the 3I input elements <textbox, combo box etc.= with the view model class properties and the 3I actions li$e button clic$, right clic$ are connected to the methods of the class by commands.
1ollapse D ,opy ,ode

Note *< 2lease re0er previous Kuestions to understand co""and and bindings.

Bhat is the difference between &22& and L layer architectureQ


.**. has an extra layer as compared to 7 layer architecture. In 7 layer architecture we have 3I <view= , business logic < model= and Data access layer < DA/=. In .**. we have an extra layer in between view and model i.e. the view model class. 7 layer architecture complements .**. architecture.

E*plain delegate commandQ


First let us answer in short: & ?Delegate command ma$es a .**. command class independent of the view model@.5ow let>s understand the long way. In .**. architecture view tal$s with the view model and view model tal$s with the model. 'hen actions are sent from the view they are sent to '0F commands for handling the events. '0F commands invo$ed methods of view model internally. In other words command needs reference of view model class. If you see a typical '0F .**. command it loo$s as shown below. #ou can see the ?1ustomer*iew.odel@ class referenced inside the Abtn1ommand@ class. If you thin$ with your eyes closed this reference of ?1ustomer*iew.odel@ class inside the command is a problem. This will lead to tight coupling between command classes and view model. If you visuali9e command it is nothing but clic$ , double clic$ , left mouse clic$ , drag and drop etc. It>s an A1TI 5 created by the user. 5ow wouldn>t be great if we can "ust attach this command with any view model. +o li$e clic$ event gets connected with ?1ustomer*iew.odel@ or ?+upplier*iew.odel@. This is achieved by using delegate command.
1ollapse D ,opy ,ode

public class btnCo""and * 1Co""and { 2rivate Custo"erJie$Model Jie$obN - ne$ Custo"erJie$Model(); public btnCo""and(Custo"erJie$Model obN) { Jie$obN - obN; } public bool CanB@ecute(obNect para"eter) 88 When he should e@ecute { return Jie$obN.1sJalid(); }

public void B@ecute(obNect para"eter) 88 What to e@ecute { Jie$9bN.Add(); } }

To decouple the view model class from command we can use delegates i.e. ?Action@ and ?Func@. If you see the command class we need only two things ?'hatto,xecute@ and ?'hento,xecute@. +o how about passing these methods as generic delegates. #ou can see the constructor of ?btn1ommand@ ta$es two delegates one what to execute and when to execute. #ou can see in the below code the ?btn1ommand@ class has no reference of the view model class but has references to delegates which are "ust abstract pointer to functions C methods. +o this command class can now be attached with any view model class. This approach is termed as ?Delegate command@.
1ollapse D ,opy ,ode

public class btnCo""and * 1Co""and 88 tep % *< Create co""and { private Action WhattoB@ecute; private 7uncHboolI WhentoB@ecute; public btnCo""and(Action What & 7uncHboolI When) { WhattoB@ecute - What; WhentoB@ecute - When;

} public bool CanB@ecute(obNect para"eter) 88 When he should e@ecute { return WhentoB@ecute(); }

public void B@ecute(obNect para"eter) 88 What to e@ecute { WhattoB@ecute(); } }

Bhat is P. S&Q
0BI+. is a framewor$ to develop composite application in '0F and +ilverlight. 1omposite applications are built using composition. In other words rather than building application from scratch we ta$e prebuilt components, assemble them together and create the application. Ta$e the below example of simple '0F 3I. #ou can see it has lots of sections. 5ow rather than building the whole 3I as one big unit, we can develop all these section as independent unit. /ater by using 0BI+. we can compose '0F 3I by ta$ing all these independent units.

Bhat are benefits of P. S&Q


.odular development: & As we are developing components as independent units we can assign these units to different developers and do modular parallel development. 'ith parallel development pro"ect will be delivered faster. 2igh reusability: & As the components are developed in individual units we can plug them using 0BI+. and create composed 3I in an easy way.

Fow are individual units combined in to a single unitQ


0BI+. uses dependency in"ection for the same. 0lease see design pattern section to read about DI <dependency in"ection=. 'e can do DI by two way>s by using unity application bloc$ or .,F < managed extensibility framewor$=.

0oes P. S& do &22&Q


The prime focus of 0BI+. is modular development and not .**.. !ut it does have readymade classes li$e delegate command which can help us reduce .**. code. !ut please note the main goal of 0BI+. was not .**..

s P. S& a part of BPFQ


5o, 0BI+. is a separate installation.

Bhat is e*pression blendQ


,xpression blend is a designing tool for '0F and +ilver/ight application.

Vous aimerez peut-être aussi