net interview questions all in one
DESCRIPTION
All the details are collected form 4-5 web site. include:--Main OOPs Concept with Example-.Net & Asp.net Cocept - MVC important Questions-Sql Server- WPFTRANSCRIPT
-
5/28/2018 .Net Interview Questions all in One
1/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 Polyorphis?
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
-
5/28/2018 .Net Interview Questions all in One
2/110
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 inthat 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)5void 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;.
-
5/28/2018 .Net Interview Questions all in One
3/110
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)?
ðod 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 dont 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 doesnt 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.
-
5/28/2018 .Net Interview Questions all in One
4/110
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.6se @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?
#S pointer refers to the current object of a class. #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 doesnt 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 bedefined. A virtual function can be declared as Pure by using the operator G.
E*ample 6.
-
5/28/2018 .Net Interview Questions all in One
5/110
2irtual void function;') !! 2irtual" /ot pure
2irtual void function
-
5/28/2018 .Net Interview Questions all in One
6/110
bstraction
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.
ccess o(ifier %escription ,ho can access7
Private Only members within the same type. 'default for type members)
Protected Only derived types or members of the same type.
nternalOnly code within the same assembly. ,an also be code e*ternal to
object as long as it is in the same assembly. 'default for types)
Protected internalEither code from derived type or code in the same assembly.
,ombination of protected O internal.
PublicAny code. /o inheritance" e*ternal type" or e*ternal assembly
restrictions.
8o(e E-aple 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" toproduce 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.iding 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
-
5/28/2018 .Net Interview Questions all in One
7/110
#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
-
5/28/2018 .Net Interview Questions all in One
8/110
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"; }
}
-
5/28/2018 .Net Interview Questions all in One
9/110
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.ere 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";}}
-
5/28/2018 .Net Interview Questions all in One
10/110
#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-plainsEncapsulation
Encapsulation in , 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 Encapsulation
Abstraction solves the problem in the designlevel.
Encapsulation solves the problem in the implementation level.
Abstraction is used for hiding the unwanted
data and giving only relevant data.
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 ofhow it does it.
Encapsulation means hiding the internal details or mechanics of how anobject 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 reers 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 interace and abstract class while Encapsulation is implemented using
-
5/28/2018 .Net Interview Questions all in One
11/110
pri&ate and protected access modiier.
2. OOPS makes use o encapsulation to enorce 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 (publicpri&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 -
-
-
5/28/2018 .Net Interview Questions all in One
12/110
bstract 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 abstractbefore 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 dont want anyone to create objects of these class
types. Dou can ma%e use of abstract classes to implement such functionality in , 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 donot have any implementation in the abstract class" but the same has to be provided in its derived
class.
abstractclassabsClass
{
publicabstractvoidabstractMethod();
}
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:abstractclassabsClass
{
publicvoidNonAbstractMethod()
{
Console.WriteLine("NonAbstract Method");
}}
A sample program that explains abstract classes:
using!ste;
naespaceabstractaple
{
//Creating an Abstract Class abstractclassabsClass
{
//A Non abstract method publicintAdd#$oNubers(intNu%& intNu')
{
returnNu% Nu';
}
//An abstract method, to be //overridden in derived class
-
5/28/2018 .Net Interview Questions all in One
13/110
publicabstractintMultipl!#$oNubers(intNu%& intNu');
}
//A Child Class of absClass classabserived*absClass
{ +#A#hread,
staticvoidMain(string+, args)
{
//You can create an //instance of the derived class
abserived calculate - ne$abserived(); intadded - calculate.Add#$oNubers(%&'); intultiplied - calculate.Multipl!#$oNubers(%&'); Console.WriteLine("Added * {}&
Multiplied * {%}"& added& ultiplied);
}
//using override keyword, //implementing the abstract method //MultiplyTwoNumbers publicoverrideintMultipl!#$oNubers(intNu%& intNu')
{
returnNu% / Nu';
} }}
n the above sample" you can see that the abstract class abs,lasscontains two
methods Add#wo/umbersand&ultiply#wo/umbers. Add#wo/umbersis a non6abstract methodwhich contains implementation and&ultiply#wo/umbersis an abstract method that does not
contain implementation.
#he class abs0erivedis derived from abs,lassand the &ultiply#wo/umbersis implemented
on abs0erived. Bithin the &ain" an instance 'calculate) of the abs0erivedis created" and
calls Add#wo/umbersand&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 Class1abstractclassabsClass%
{
publicabstractintAdd#$oNubers(intNu%& intNu'); publicabstractintMultipl!#$oNubers(intNu%& intNu');
}
//Abstract Class
abstractclassabsClass'*absClass%
{
//!mplementing AddTwoNumbers publicoverrideintAdd#$oNubers(intNu%& intNu')
{ returnNu%Nu';
}
-
5/28/2018 .Net Interview Questions all in One
14/110
}
//"erived class from absClass
classabserived*absClass'
{
//!mplementing MultiplyTwoNumbers
publicoverrideintMultipl!#$oNubers(intNu%& intNu')
{
returnNu%/Nu';
}}
Inthe above e*ample" abs,lass; contains two abstract methods Add#wo/umbersand &ultiply#wo/umbers.#heAdd#wo/umbersis implemented in the derived class abs,lass
-
5/28/2018 .Net Interview Questions all in One
15/110
abstractsealedclassabsClass
{
}
Declaration of abstract methods are only allowed in abstract classes.
An abstract method cannot be private.//!ncorrectprivateabstractintMultipl!#$oNubers();
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 protectedin 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
publicabstractvirtualintMultipl!#$oNubers();
An abstract member cannot be static.//!ncorrectpublpublic abstractstaticintMultipl!#$oNubers();
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:
inter0aceiaple1nter0ace
{
//All methods are automaticall abstract intAddNubers(intNu%& intNu'); intMultipl!Nubers(intNu%& intNu');
}
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 oldversion. 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.
bstract etho(
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 methodname 'as abstract method name) to provide further implementation of abstract methods.
:on bstract etho(
n an abstract class a method which doesnKt have a %eyword JabstractJ and provide any
-
5/28/2018 .Net Interview Questions all in One
16/110
implementation is called non abstract method.
Why bstract 8lass
Abstract class enforces derived classes to provide all implementation logic for abstract methods or
properties.
-
5/28/2018 .Net Interview Questions all in One
17/110
but the superclass itsel will ne&er e"ist. 1or e"ample, a class 2ersonwill ne&er e"ist. 2owe&er a
class Woanwill. /nstead o repeating all the methods that are in Woan, 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 perorm dierentl#.
Interfaces
/nteraces 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 /nterace, will ha&e to pro&ide code or a certain
number o methods.
1or e"ample, A class 5oc6and a class 3allcan 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/nterace (/ didn4t want to use the word #hro$ableor ob&ious reasons), then the
method can just accept an object o t#pe #hro$ing1teand 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 interace.
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.
.:E; ,ith e-aple
Bhen you want to allow a derived class to override a method of the base class" within the base classmethod 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 optionalfor 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.
ðod overriding also provides more than one form for a method. ence it is also an e*ample for
polymorphism.
;he follo,in) e-aple creates three classes shape circle an( rectan)le ,here circle an(
-
5/28/2018 .Net Interview Questions all in One
18/110
rectan)le are inherite( fro the class shape an( o'erri(es the etho(s rea7 an(
8ircuference7 that are (eclare( as 'irtual in Shape class.
usingSystem5namespaceProgram,all
8 classShape
8 pro tec te dfloat" $" @5
pub lic virtual float Area') 8
returnL.;MF 7 7 5 9
pub lic virtual float ,ircumference') 8
return< 7 L.;MF 7 5 9
9 classectangle: Shape
8
pub lic voidNet$@')
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
pub lic override floatArea') 8
return$ 7 @5 9
pub lic override float,ircumference')
8 return< 7 '$ 3 @)5 9
9 class,ircle: Shape
8 pub lic voidNetadius')
8
,onsole.Brite'JEnter adius : J)5
float.Parse',onsole .ead$ine'))5
9 9
class&ain,lass
8 staticvoid&ain')
8 ectangle ne wectangle ') 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,.Netadius')5
,onsole.Brite$ine'JArea : 8G9J" ,.Area'))5
,onsole.Brite$ine'J,ircumference : 8G9J" ,.,ircumference'))5 ,onsole.ead')5 9
9
-
5/28/2018 .Net Interview Questions all in One
19/110
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 thevirtual %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. ence 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.
etho( 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 ofarguments 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, butwants 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 twooptions,virtual methods and abstract methods.
xamples for Method !verriding in C#usingSystem5
namespace methodoverriding8
class@ase,lass 8
pub lic virtual string Dour,ity') 8
returnJ/ew Dor%J5 9
9 class0erived,lass : @ase,lass
-
5/28/2018 .Net Interview Questions all in One
20/110
8 pub lic override stringDour,ity')
8 returnJ$ondonJ 5
9 9
classProgram
8 staticvoid&ain'stringTU args) 8
0erived,lass obj new0erived,lass ') 5 stringcity ob j.Dour,ity')5
,onsole.Brite$ine'city)5
,onsole.ead')5
9 9
9
Output
$ondon
E*ample 6 < implementing abstract method
usingSystem5
namespace methodoverridinge*ample
8 abstract class@ase,lass
8 pub lic abstract stringDour,ity')5
9
class0erived,lass : @ase,lass 8
pub lic override stringDour,ity') !!t is mandatory to implement absract method 8
returnJ$ondonJ 5
9
pri va teint sum'int a" in tb )
8 returna 3 b5
9 9
classProgram 8
staticvoid&ain'stringTU args) 8 0erived,lass obj new0erived,lass ') 5
stringcity ob j.Dour,ity')5 ,onsole.Brite$ine'city)5
,onsole.ead')5 9
99
Output$ondon
-
5/28/2018 .Net Interview Questions all in One
21/110
"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 JEmployeeJ 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 @ors of ipleentin) interface
#here are two of ways of implementing interfaces
E*plicit
mplicit
E-plicit interface ipleentation
#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!!!!!"; }
-
5/28/2018 .Net Interview Questions all in One
22/110
}
"n ,hich scenario ,e use e-plicit interface ipleentation
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'JEmployee 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 , class may only inherit from one class.
-
5/28/2018 .Net Interview Questions all in One
23/110
Feature nterface Abstract class
&ultiple inheritance A class may inherit several
interfaces.
A class may inherit only
one abstract class.
0efault implementation An interface cannot
provide any code" just thesignature.
An abstract class can
provide complete" defaultcode and!or just the details
that have to be overridden.
Access &odfiers An interface cannot have
access modifiers for the
subs" functions" properties
etc everything is assumed
as public
An abstract class can
contain access modifiers
for the subs" functions"
properties
,ore 2S Peripheral nterfaces are used to
define the peripheralabilities of a class. n other
words both uman and
2ehicle can inherit from a
&ovable interface.
An abstract class defines
the core identity of a classand there it is used for
objects of the same type.
omogeneity f various implementations
only share method
signatures then it is better
to use nterfaces.
f various implementations
are of the same %ind and
use common behaviour or
status then abstract class is
better to use.
Speed e1uires more time to find
the actual method in the
corresponding classes.
Fast
Adding functionality
'2ersioning)
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.
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.
Fields and ,onstants /o fields can be defined in
interfaces
An abstract class can have
fields and constrants
defined
-
5/28/2018 .Net Interview Questions all in One
24/110
Polyorphis 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 ," 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
P o l y m o r p h i s m E * a m p l e s
etho( O'erloa(in)
etho( O'erri( in)
,ompile time Polymorphism or Early @inding
#he polymorphism in which compiler identifies w hich 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 w hich 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.
http://msdn.microsoft.com/en-us/library/ms173152(v=VS.80).aspxhttp://www.programcall.com/24/csnet/method-overloading-in-csnet.aspxhttp://www.programcall.com/25/csnet/method-overriding-in-csnet.aspxhttp://msdn.microsoft.com/en-us/library/ms173152(v=VS.80).aspxhttp://www.programcall.com/24/csnet/method-overloading-in-csnet.aspxhttp://www.programcall.com/25/csnet/method-overriding-in-csnet.aspx -
5/28/2018 .Net Interview Questions all in One
25/110
Static 8lass
Astaticclass 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 tility,lassthat has a
public method named ðodA" you call the method as shown in the following e*ample:tility,lass.ðodA')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 staticSystem.&athclass contains methods that perform mathematical
operations" without any re1uirement to store or retrieve data that is uni1ue to a particular instance of
the&athclass. #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 9utput*
88 :.%
88
-
5/28/2018 .Net Interview Questions all in One
26/110
public static class #emperature,onverter
{
public static double Celsius#o7ahrenheit(string teperatureCelsius)
{
88 Convert arguent to double 0or calculations.
double celsius - ouble.2arse(teperatureCelsius);
88 Convert Celsius to 7ahrenheit.
double 0ahrenheit - (celsius / = 8 >) :';
return 0ahrenheit;
}
public static double 7ahrenheit#oCelsius(string teperature7ahrenheit)
{
88 Convert arguent to double 0or calculations.
double 0ahrenheit - ouble.2arse(teperature7ahrenheit);
88 Convert 7ahrenheit to Celsius.
double celsius - (0ahrenheit < :') / > 8 =;
return celsius;
}
}
class #est#eperatureConverter
{
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 teperature* ");
7 - #eperatureConverter.Celsius#o7ahrenheit(Console.5eadLine());
Console.WriteLine("#eperature in 7ahrenheit* {*7'}"& 7);
brea6;
case "'"* Console.Write("2lease enter the 7ahrenheit teperature* ");
C - #eperatureConverter.7ahrenheit#oCelsius(Console.5eadLine());
Console.WriteLine("#eperature 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!();
}
}
-
5/28/2018 .Net Interview Questions all in One
27/110
Static you can use the method of the class which is static, but you ma"e sure that the valuegets changed as you reuired.
$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 entireapplication 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.ule>2. a method should be static i.e. the method declaration must contain the static %eyword.
ule>3. the ,onstructor must be static because a static class doesnKt allow an instance constructor.
ule>4. the ,onstructor must not contain an access modifier.
ule>5. a Static class canKt implement an inteface.
ule>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 ebers ust be created as static. 1n other $ords&
!ou cannot add a non;
}
http://msdn.microsoft.com/en-us/library/e6w8fe1b.aspxhttp://msdn.microsoft.com/en-us/library/e6w8fe1b.aspx -
5/28/2018 .Net Interview Questions all in One
28/110
}
public static void rive() { }
public static event Bvent#!pe 5un9ut904as;
88 9ther non
-
5/28/2018 .Net Interview Questions all in One
29/110
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 //objectCount = 1
Point origin< new Point')5 //objectCount = 2
-
5/28/2018 .Net Interview Questions all in One
30/110
Point originL new Point')5 //objectCount = 3
ere 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 newX %eyword) of this class.
t can have a default constructor and it is also static.
E-aple
$et us consider an e*ample.
Point.cs
using System5
using System.,ollections.Neneric5using System.#e*t5
namespace ,onApp,Y,,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')
-
5/28/2018 .Net Interview Questions all in One
31/110
8
return object,ount5
9
private int *" y5 private static int object,ount G5
9
9
8onstructorE-aple.cs
using System5
using System.,ollections.Neneric5
using System.#e*t5
namespace ,onApp,Y,,ons
8
class ,onstructorE*ample
8
static void &ain'stringTU args)
8
Point origin new Point')5
Point bottomight new Point';G
-
5/28/2018 .Net Interview Questions all in One
32/110
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 internalcan be access by any member within application. t is thedefault access specifiers for a class in , programming.
usingSystem;
namespace)nternal_.ccess_Specifier/
classaccess
/
77 String $ariable declared as internal
internalstringname;
publicvoidprint(
/
Console!rite#ine("8nMy name is "9 name; }
}
class:rogram
/
staticvoidMain(string< args
/
accessac = ne%access(;
Console!rite("+nter your name8t";
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 sae assebl!
internal static int @ - ;}
#ypes or members that have access modifier protecte( internalcan be accessed from the current
assembly or from types that are derived from the containing class.
For a comparison of internalwith the other access modifiers" see Accessibility $evels ',
eference)and Access &odifiers ', Programming Nuide).
For more information about assemblies" see Assemblies and the Nlobal Assembly ,ache ', 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 applicationcode. 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%.
http://msdn.microsoft.com/en-us/library/wxh6fsc7.aspxhttp://msdn.microsoft.com/en-us/library/ba0a1yw2.aspxhttp://msdn.microsoft.com/en-us/library/ba0a1yw2.aspxhttp://msdn.microsoft.com/en-us/library/ms173121.aspxhttp://msdn.microsoft.com/en-us/library/ms173099.aspxhttp://msdn.microsoft.com/en-us/library/ms173099.aspxhttp://msdn.microsoft.com/en-us/library/wxh6fsc7.aspxhttp://msdn.microsoft.com/en-us/library/ba0a1yw2.aspxhttp://msdn.microsoft.com/en-us/library/ba0a1yw2.aspxhttp://msdn.microsoft.com/en-us/library/ms173121.aspxhttp://msdn.microsoft.com/en-us/library/ms173099.aspxhttp://msdn.microsoft.com/en-us/library/ms173099.aspx -
5/28/2018 .Net Interview Questions all in One
33/110
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 Tnternals2isible#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 Assebl!%.cs
88 Copile $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 constructorwill be called the first time the class is accessed statically.
a constructor with an internalaccess 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 publicaccess 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 classis 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 .*Tthe *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
sealedclassealedClass{
http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspxhttp://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx -
5/28/2018 .Net Interview Questions all in One
34/110
}$n the following code, $ create a sealed class SealedClass and use it from Class-. $f you runthis code then it will wor" fine. )ut if you try to derive a class from the SealedClass, you will
get an error.using!ste;classClass%{
staticvoidMain(string+, args)
{
ealedClasssealedCls - ne$ealedClass(); inttotal - sealedCls.Add(& >);
Console.WriteLine("#otal - " total.#otring());
}}88 ealed class
sealedclassealedClass{
publicintAdd(int@& int!) {
return@ !; }}MSDN Updated
Sealed Methods and PropertiesYou 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 classand prevent other developers that are using your classes from overriding specific virtualmethods and properties.
classD
{
protectedvirtualvoid7() { Console.WriteLine("D.7"); }
protectedvirtualvoid7'() { Console.WriteLine("D.7'"); }
}
classE * D
{
sealedprotectedoverridevoid7() { Console.WriteLine("E.7"); }
protectedoverridevoid7'() { Console.WriteLine("D.7:"); }
}
classF * E
{
88 Attepting to override 7 causes copiler error C':=.
88 protected override void 7() { Console.WriteLine("C.7"); }
88 9verriding 7' is allo$ed.
protectedoverridevoid7'() { Console.WriteLine("F.7'"); }
}
Why Sealed Classes?
-
5/28/2018 .Net Interview Questions all in One
35/110
We %ust saw how to create and use a sealed class. The main purpose of a sealed class is tota"e away the inheritance feature from the user so they cannot derive a class from a sealedclass. !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. orexample, /&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 classesto 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 baseclass" 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 Bplo!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 declaredsealed" 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
http://msdn.microsoft.com/en-us/library/wbx7zzdd.aspxhttp://msdn.microsoft.com/en-us/library/wbx7zzdd.aspx -
5/28/2018 .Net Interview Questions all in One
36/110
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:publicpartialclassA { }
88public class A { } 88 Brror& ust also be ar6ed partial
#he partialmodifier 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:
partialclassClassWithNestedClass
{
partialclassNestedClass { }
}
partialclassClassWithNestedClass
{
partialclassNestedClass { }
}
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 onone 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 lie easier on code generators designers. Partial classes
http://msdn.microsoft.com/en-us/library/yzh058ae.aspxhttp://msdn.microsoft.com/en-us/library/st6sy9xe.aspxhttp://msdn.microsoft.com/en-us/library/bcd5672a.aspxhttp://msdn.microsoft.com/en-us/library/7c5ka91b.aspxhttp://msdn.microsoft.com/en-us/library/sf985hc5.aspxhttp://msdn.microsoft.com/en-us/library/88c54tsw.aspxhttp://msdn.microsoft.com/en-us/library/51y09td4.aspxhttp://msdn.microsoft.com/en-us/library/yzh058ae.aspxhttp://msdn.microsoft.com/en-us/library/st6sy9xe.aspxhttp://msdn.microsoft.com/en-us/library/bcd5672a.aspxhttp://msdn.microsoft.com/en-us/library/7c5ka91b.aspxhttp://msdn.microsoft.com/en-us/library/sf985hc5.aspxhttp://msdn.microsoft.com/en-us/library/88c54tsw.aspxhttp://msdn.microsoft.com/en-us/library/51y09td4.aspx -
5/28/2018 .Net Interview Questions all in One
37/110
allow the generator to simpl# emit the code the# need to emit and do not ha&e to deal with user edits tothe ile. 5sers are likewise ree to annotate the class with new members b# ha&ing a second partialclass. his pro&ides a &er# clean ramework or separation o concerns.
A better wa# to look at it is to see how designers unctioned beore 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 conidence 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.
-
5/28/2018 .Net Interview Questions all in One
38/110
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 generatedcode 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.
-
5/28/2018 .Net Interview Questions all in One
39/110
without committing to actual data t#pes. his results in a signiicant perormance boost and higher3ualit# code, because #ou get to reuse data processing algorithms without duplicating t#pe'speciiccode. /n concept, generics are similar to !99 templates, but are drasticall# dierent in implementationand capabilities.1enerics provide the solution to a limitation in earlier versions of the common languageruntime and the C# language in which generali2ation is accomplished by casting types to andfrom the universal base type !b%ect. )y creating a generic class, you can create a collectionthat is type-safe at compile-time.
The limitations of using non3generic collection classes can be demonstrated by writing a shortprogram that ma"es use of the .rray#istcollection class from the .*T ramewor" base class
library. .rray#istis a highly convenient collection class that can be used without modification
to store any reference or value type.
using System;using System!Collections;using System!Collections!eneric;using 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
Listint) list1 # new Listint)(!
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= ,; }
-
5/28/2018 .Net Interview Questions all in One
40/110
} }}
Genericsallow 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
sing 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.Genericnamespace. 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 acollection of ob%ects. 4rrays are good for many tas"s, but C# v7.6 introduced a new feature calledgenerics. 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 theycan 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"istfor wor"ing with
groups of ob%ects. 4n!rray"istis much li"e an array, except it could automatically grow and offeredmany convenience methods that arrays don't have. The problem with!rray"istand all the other .*Tv-.6 collections is that they operate on typeob#ect. Since all ob%ects derive from the ob#ecttype, you can
assign anything to an!rray"ist. The problem with this is that you incur performance overhead convertingvalue type ob%ects to and from the ob#ecttype and a single!rray"istcould 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 intoit. This eliminates type mismatches at runtime. 4nother benefit of type safety is that performance isbetter with value type ob%ects because they don't incur overhead of being converted to and fromtype ob#ect. With generic collections, you have the best of all worlds because they are strongly typed, li"earrays, and you have the additional functionality, li"e!rray"istand other non3generic collections, withoutthe problems.
The next section will show you how to use a generic "istcollection.
-
5/28/2018 .Net Interview Questions all in One
41/110
8reatin) GenericList8ollections
#he pattern for using a genericistcollection is similar to arrays. Dou declare theist" populate its
members" then access the members. ereKs a code e*ample of how to use a ist:
$ist(int+ mynts new $ist(int+')5
mynts.Add';)5 mynts.Add'
-
5/28/2018 .Net Interview Questions all in One
42/110
#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 theclass implements Enumerable" you donKt need to %now the hows or the whys). suggest you read
up on interfaces and so forth.
1Bnuerableis a general'purpose interace that is used b# man# classes, such
as Arra!, Listand tringin order to let someone iterate o&er a collection. :asicall#, it4s what dri&es
the 0oreachstatement.
1Listis t#picall# how #ou e"pose &ariables o t#pe Listto end users. his interace permits random
access to the underl#ing collection.
"Enuerable
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 .5T Framewor$ type. It is slower than the
generic ictionar!type.
using+ystem.1ollections;class2rogra
{
staticGashtable 4etGashtable()
{
//Create and return new #ashtable$ Gashtable hashtable - ne$Gashtable(); hashtable.Add("Area"& %); hashtable.Add("2erieter"& >>);
-
5/28/2018 .Net Interview Questions all in One
43/110
hashtable.Add("Mortgage"& >); returnhashtable;
}
public staticvoidMain()
{
Gashtable hashtable - 4etGashtable();
//%ee if the #ashtable contains this key$ Console.WriteLine(hashtable.Contains?e!("2erieter")); //Test the Contains method$ !t works the same way$ Console.WriteLine(hashtable.Contains("Area")); //&et value of Area with inde'er$ intvalue - (int)hashtable+"Area",; //(rite the value of Area$
Console.WriteLine(value);
}
}
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
reuires 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.
classDict
{
staticvoidMain()
{
//)'ample "ictionary again
ictionar!Hstring& intI d - ne$ictionar!Hstring& intI() {
{"Lion"& '}& {"dog"& %}}; //*oop over pairs with foreach 0oreach(?e!Jalue2airHstring& intI pair ind)
{
Console.WriteLine ("{}& {%}"&pair.?e!& pair.Jalue);
}
0oreach(varpair ind)
{
Console.WriteLine("{}& {%}"& pair.?e!& pair.Jalue);
}
Console.5ead?e!();
}
}
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.
-
5/28/2018 .Net Interview Questions all in One
44/110
It is slower than dictionary because it reuires 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.
-
5/28/2018 .Net Interview Questions all in One
45/110
#ypes of inheritance in c
#here are C types of inheritance as shown below.
;.Single nheritance
-
5/28/2018 .Net Interview Questions all in One
46/110
&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
; classeadOffice8
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.
-
5/28/2018 .Net Interview Questions all in One
53/110
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 inaliDemethod 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 callsthe inali2e method to free the memory used by such ob%ects. The *isposemethod is called by the
programmer.*isposeis 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 *isposemethod can be
invo"ed only by the classes that implement the )*isposableinterface.
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$T compiler is an important element of C5$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
subseuent 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.*tringand *ystem.*tringuilder classes?
Stringand String&uilderclasses are used to store string values but the difference in them is thatString 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 Stringob%ect. !n the other hand, the String&uilderclass
-
5/28/2018 .Net Interview Questions all in One
56/110
is mutable, as it occupies the same space even if you change the value. The String&uilderclass 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 ofrespective 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 intand int>F. System!)nt>Fis a .*T Class and intis an alias name
forSystem!)nt>F.
SP.:E;
Concept of Postback in ASP!"$
A postbac$ is a reuest sent from a client to server from the same page user is already wor$ing with.A+0.5T was introduced with a mechanism to post an 2TT0 0+T reuest bac$ to the same page. It(s
basically posting a complete page bac$ to server
-
5/28/2018 .Net Interview Questions all in One
57/110
"nit8oplete9
#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 Pageobject calls the On$oadmethod on the Pageobject itself" later the On$oadmethod of thecontrols is called.
#hus $oadevent of the individual controls occurs after the $oadevent of the page.
8ontrolE'ents9
#his event is used to handle specific control events such as a @uttoncontrols ,lic%event or
a #e*t@o*controls #e*t,hangedevent.n case of postbac%:
f the page contains validator controls" the Page.s2alidproperty and the validation of the controls ta%es placebefore the firing of individual control events.
Hoa(8oplete9
#his event occurs after the event handling stage.
#his event is used for tas%s such as loading all other controls on the page.
Preen(er9
n this event the Preenderevent of the page is called first and later for the child control.sage:
#his method is used to ma%e final changes to the controls on the page li%e assigning the 0ataSourcedand
calling the 0ata@indmethod.
Preen(er8oplete9
#his event is raised after each controlKs Preenderproperty is completed.
Sa'eState8oplete9
#his is raised after the control state and view state have been saved for the page and for all controls.
en(er8oplete9
#he page object calls this method on each control which is present on the page.
#his method writes the controls mar%up to send it to the browser.
-
5/28/2018 .Net Interview Questions all in One
58/110
+ection vent Description
be raised on each reuest.
GttpModule Authenticate5eKuest
This event signals that A+0.5T runtime is ready to
authenticate the user. Any authentication code can
be in"ected here.
GttpModule Authorie5eKuest This event signals that A+0.5T runtime is ready toauthori9e the user. Any authori9ation code can be
in"ected here.
GttpModule 5esolve5eKuestCache
In A+0.5T, we normally use outputcache directive to
do caching. In this event, A+0.5T 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.
GttpModule AcKuire5eKuesttate
This event signals that A+0.5T runtime is ready to
acuire session variables. Any processing you would
li$e to do on session variables.
GttpModule 2re5eKuestGandlerB@ecute
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.
GttpGandler 2rocess5eKuest
Gttphandler logic is executed. In this section, we
will write logic which needs to be executed as per
page extensions.
2age 1nit
This event happens in the A+0.5T 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 viewstat