Chapter 1: Top 50 Technical and Non-Technical Questions: See Our Other Step by Step Video Series Below
Chapter 1: Top 50 Technical and Non-Technical Questions: See Our Other Step by Step Video Series Below
Chapter 1: Top 50 Technical and Non-Technical Questions: See Our Other Step by Step Video Series Below
com
Call on +91-22-66752917 / +91-9967590707
.NET Interview Questions
BY
www.questpond.com
See our other step by step video series below.
Learn ASP.NET MVC 5 Step by Step: ‐ https://goo.gl/sWmzBU
Learn AngularJS Step by Step: ‐ https://goo.gl/WMhWbF
Learn Design Pattern in 8 hours: ‐ https://goo.gl/Lqdn1S
Learn C# and .NET in 60 days: ‐ https://goo.gl/iPIW8v
Learn MSBI in 32 hours: ‐ https://goo.gl/euKRT3
Learn SharePoint Step by Step: ‐ https://goo.gl/pc7phf
Note: - I think 40% ( the percentage can be higher) .NET interview starts
with this question. Below is a sample answer and will differ from developer
to developer.
My current architecture is a 3 tier architecture with UI made in ASP.NET, middle tier having the
business logic and the data access layer uses enterprise data application blocks. It uses MVC
architecture to keep the UI code clean.
We also have a common library which is shared in our project and for external customer we have
exposed some service via WCF.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Whatrole did you play in your project and company?
My role was end to end. I was involved right from the requirement phase where I was a part of
requirement gathering and creating use cases.
I was also actively involved in design phase to conceptualize the technical aspect of the project.
My main role was then in development / coding phase where I was involved in coding and unit testing.
I also played an important role in system and acceptance testing to fix defects and issues raised by testers
and end users.
So my role was end to end with main focus on coding and unit testing.
I am also partly involved with the COE group where I help developers in the company to upgrade to new
technologies.
Note: - If you are a part of other activities like training , quality , pre-
sales team , estimation etc speak about the same during interview.Companies
now a day’s look out for multitasking capabilities rather than specific
capabilities.
This is a very complex question at the end of the book we have a complete chapter which
discusses specifically on current .NET developer salary packages and some tips for negotiation.
One golden tip from me, if you really want the job and you do not want salary to be a hurdle ,
add the word “NEGOTIABLE” after the salary amount.
This is a subjective answer and varies from individual to individual. Some answers which can explain
your current situations:-
• For better prospects.
• Expecting a salary rise.
• Relocation.
• Looking for a better position.
• Had a kid ( For women’s)
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Note:- Do not give answers like company was not good , there was too much
politics , it was a maintenance job etc etc. These answers can lead to more
cross questions making the interviewer uncomfortable.
Note:-This questions comes in different forms like, How much do you rate
yourself in ASP.NET , How much do you rate yourself in SQL Server etc.
Answer for this question is again very subjective but some important tricks here to avoid any traps.
• Even if you are really good in that topic do not rate yourself 10 or 9, just shows that you are
overconfident. If you are extremely good put 8. Let your technical answers talk about your
rating.
• If you know the topic averagely, rate yourself 5.
• If you are bad in the topic or have never done anything do not put any rating. Probably it’s better to
say you have not worked rather than trying to attempt and create more problems.
Note:- Many people become emotional here and talk personal. Most of the time
interviewer is expecting to talk about your role you played , technological
skills and which path you want to grow. Below is a sample answer and it
varies from person to person.
I have 8 years of experience, in the first 4 years I worked as a developer in Microsoft technologies. The
next 2 years after that I worked as a team lead guiding the team, helping them resolve problems. Currently
I am working in Microsoft server products like SharePoint,BizTalk. My main technical skills revolve
around C#, Visual studio, SQL Server, .NET and ASP.NET.
I would like to see myself as technical lead in further coming times.
Note:- The last sentence is very important , let the interviewer know where
you want to see yourself in the later stages.
Note:-This question can have various other forms like How can we improve
performance of ASP.NET , How can we improve performance of SQL Server etc.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Remember 5 best points of each category. You can pick your favorite ones. But
whatever you pick , should be commonly used by every one.
Below are some common points you can remember. List is endless but I do not want to make it
long, so that you can remember important ones.
• Use string builder for concatenation rather than string when concatenation huge string
values.
• Avoid boxing / unboxing, use generics.
• Avoid writing in line SQL queries use stored procedures.
• Choose your indexes (clustered and non-clustered) properly.
• Use Caching for data which will not change frequently.
• In ASP.NET use output cache directive for page level caching.
Below is the list of top differences between the framework versions. Please remember the list is
much bigger than what I have put down. But for interview perspective I have taken top 5 in each
one of them so that we can remember the important ones.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
• CAS is the part of .NET security model which determines whether or not a particular
code is allowed to run and what kind of resources can the code access.
Note: - Do have a look at the video What is IL code, CLR, CTS, CLS and JIT?
There are two parts to this video in the first part we have discussed the
theory in the next part we have discussed practically how these terminology
come to life in .NET environment.
Garbage collector is a feature of CLR which cleans unused managed (it does not clean unmanaged
objects) objects and reclaims memory. It’s a back ground thread which runs continuously and at specific
intervals it checks if there are any unused objects whose memory can be claimed.
Note: - Do have a look at the video What is Garbage collector, Gen 0, 1 and
2 , which is in the DVD?
What is GAC?
GAC (Global Assembly Cache) is where all shared .NET assembly resides. GAC is used in the following
situations:-
• If assemblies have to be shared among several applicationwhich resides in the same computer.
• If the assembly has some special security, requirements like only administrators can remove
the assembly. If the assembly is private then a simple delete of assembly the assembly file
will remove the assembly.
Note :- Do have a look at two classic videos shipped in the DVD which shows
how garbage collector works internally.
What is Garbage Collector, Gen 0, 1 & 2 ?
What is IDisposable interface & finalize dispose pattern in GC?
Stack and heap are memory types in an application. Stack memory stores data types like int ,
double , Boolean etc. While heap stores data types like string and objects.
For instance when the below code runs the first two variables i.e. “i” and “y” are stored in a stack
and the last variable “o” is stored in heap.
void MyFunction()
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
{
int i = 1; // This is stored in stack.
int y = i; // This is stored in stack.
object o = null; // This is stored in heap.
} // after this end the stack variable memory space is reclaimed while //
the heap memory is reclaimed later by garbage collector.
Value types contain actual data while reference types contain pointers and the pointers point to
the actual data.
Value types are stored on stack while reference types are stored on heap. Value types are your
normal data types like int , bool , double and reference types are all objects.
When value type is moved to a reference type it’s called as boxing. The vice-versa is termed as
unboxing.
Note :- Watch indepth videos given in the CD What is a stack, Heap, Value
types and Reference types and What is boxing and unboxing?. These videos
example explain step by step concept of boxing , unboxing , value , reference
types , stack and heap.
try
{
// This section will have the code which
// which can throw exceptions.
}
catch(Exception e)
{
// Handle what you want to
// do with the exception
label.text = e.Message;
}
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
What are different types of collections in .NET?
There are five important collections in .NET Arrays, Lists, Hashtable , stacks and queues .
Generics help to separate logic and data type to increase reusability. In other words you can create a class
whose data type can be defined on run time.
Abstraction
Abstraction means show only what is necessary. Example color is abstracted to RGB. By just making the
combination of these three colors we can achieve any color in world. It is a model of real world or
concept.
Encapsulation
It is a process of hiding all the complex processing from the outside world and make your objects simple.
Inheritance
It’s a property of object to act differently under different conditions. For instance a simple user
object depending on conditions can act like a admin or like data entry object.
Note :- Watch the video Can you define OOP and the 4 principles of OOP? for
more detail explanation.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
relationship.
Variable declaration We can declare variables In interface we cannot declare variables.
Inheritance VS Abstract classes are inherited. Interfaces are implemented.
Implementation
There are 2 kinds of polymorphism static and dynamic. Many people also call them as runtime or
compile time polymorphism. Static polymorphism is implemented by overloading while
dynamic polymorphism is implemented by overriding and virtual keyword.
Note: -Do watch the video “What is Polymorphism, overloading, overriding and
virtual?” for in depth demonstration of how to implement polymorphism in
.NET. The video also talks about two different types of polymorphism in
depth.
Delegate is an abstract strong pointer to a function or method while events are higher level of
encapsulation over delegates. Events use delegates internally.
They differ for the below reasons:-
• Actually, events use delegates in bottom. But they add an extra layer on the delegates, thus forming
the publisher and subscriber model.
• As delegates are function to pointers, they can move across any clients. So any of the clients can add
or remove events, which can be confusing. But events give the extra protection / encapsulation by
adding the layer and making it a publisher and subscriber model.
Just imagine one of your clients doing this
c.XyzCallback = null
This will reset all your delegates to nothing and you have to keep searching where the error is.
Note :- Do watch the below three videos given in the CD to get more insight
on delegates and events.
http://www.questpond.com
For more ma
aterials on
o .NET, mail
m us questpond
q d@questp
pond.com
m
Call on +91-22-667552917 / +91-99675907077
What pro
oblem does
s Delegate Solve? - Part1
What is a Multica
ast delegat
te? - Part
t2
What are
e events & what's th
he differe
ence betwee
en delegat
tes & event
ts? - Part
t3
h
http://www
w.questpo
ond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Can you explain connection, command, datareader and dataset inADO.NET
?
• Connection: - This object creates a connection to the database. If you want to do any operation on the
database you have to first create a connection object.
• Command: - This object helps us to execute SQL queries against database. Using command object we
can execute select, insert, update and delete SQL command.
• Data reader: - This provides a recordset which can be browsed only in forward direction. It can only
be read but not updated. Data reader is good for large number of records where you want to just
browse quickly and display it.
• Dataset object: - This provides a recordset which can be read back and in forward direction. The
recordset can also be updated. Dataset is like a in memory database with tables, rows and fields.
• Data Adapter: - This object acts as a bridge between database and dataset; it helps to load the dataset
object.
• “Dataset” is a disconnected architecture, while “Data Reader” has live connection while reading data.
If we want to cache data and pass to a different tier “Dataset” forms the best choice and it has
decent XML support.
• When application needs to access data from more than one table “Dataset” forms the best choice.
• If we need to move back while reading records, “data reader” does not support this functionality.
• However, one of the biggest drawbacks of Dataset is speed. As “Dataset” carry considerable overhead
because of relations, multiple table’s etc speed is slower than “Data Reader”. Use “Data Reader”
when you want to quickly read and display records on a screen.
• Dataset can manipulate data while data reader is only for reading purpose.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Note :- Watch the complete video of Can you explain ASP.NET application and
Page life cycle ?
Handlers and modules helps you inject pre-processing logic before the ASP.NET request reaches the
website.
For instance before your request reaches any resource you would like to check if the user has been
authenticated or not.
Httphandlers is an extension based processor. In other words the pre-processing logic is invoked
depending on file extensions.
Httpmodule is an event based processor. In other words ASP.NET emits lot of event like
BeginRequest, AuthenticateRequest etc, we can write logic in those events using Httpmodule.
Note :- Watch the complete video of Can you explain ASP.NET application and
Page life cycle ? where we have explained handlers and modules in depth.
http://www.questpond.com
For more ma
aterials on
o .NET, mail
m us questpond
q d@questp
pond.com
m
Call on +91-22-667552917 / +91-99675907077
How is ‘Server.T
Transfer’ different
d frrom ‘resp
ponse.Red
direct’ ?
In “Serverr.Transfer” fo
ollowing is thhe sequence of how navigattion happens::-
1. User
U sends a reequest to naviigate to otherr page.
2. Server createss the page obbject, executees the compllete page lifee cycle and creates
c the HTML
H
ouutput.
3. The
T outputHTM
ML response is then sent back
b to the cliient browser.
Now let’ss says we wan nt to navigate between pagges which resiide on differeent servers. Noow in this sceenario
the serverr cannot creatte object of thhat page as thhe page is loccated on som
me other serveer. On that exxternal
server thiss server has no
n control. Soo for external navigation
n we need to use “Response.RRedirect”.
h
http://www
w.questpo
ond.com
For more ma
aterials on
o .NET, mail
m us questpond
q d@questp
pond.com
m
Call on +91-22-667552917 / +91-99675907077
So whe
en to use “Server.T
Transfer” and
a when to use “R
Response.Redirect”” ?
Use “Serrver.Transfer”” when you want to navvigate pages which residdes on the same s server , use
‘Responsee.Redirect’ when
w you wantt to navigate between
b pagees which residdes on differeent server.
Respon
nse.Redire
ect(URL,true) vs Re
esponse.R
Redirect(U
URL,false) ?
h
http://www
w.questpo
ond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Response.Redirect(URL,false) :- Client is redirected to a new page and the current page on the server will
keep processing ahead.
Response.Redirect(URL,true) :- Client is redirected to a new page but the processing of the current page
is aborted.
Note: - Watch the 6 videos which talks in depth about the above concepts. Its
possible that interviewer can get in to details.
What is Authentication, Authorization, Principal & Identity objects? Part-1
ASP.NET Authentication and Authorization Video series Part-2
ASP.NET Authentication and Authorization Video series Part-3
ASP.NET Authentication and Authorization Video series Part-4
ASP.NET Authentication and Authorization Video series Part-5
ASP.NET Authentication and Authorization Video series Part-6
Grid view and data grid by default display all the data in tabular format i.e. in table and rows. Developer
has no control to change the table data display of datagrid.
Data list also displays data in a table but gives some flexibility in terms of displaying data row wise and
column wise using the repeat direction property.
Repeater control is highly customizable. It does not display data in table by default. So you can
customize from scratch the way you want to display data.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
• SQL SERVER: - In this mode Session, state is serialized and stored in a SQL Server database.
Session state can be specified in <sessionState> element of application configuration file. Using State
Server and SQL SERVER session state can be shared across web farms but note this comes at speed cost
as ASP.NET needs to serialize and deserialize data over network repeatedly.
There are twoways of caching output cache directive and using the cache objects.
What is ViewState?
Viewstate is a built-in structure for automatically retaining values amongst the multiple requests for the
same page. The viewstate is internally maintained as a hidden field on the page but is hashed, providing
greater security than developer-implemented hidden fields do.
What are indexes and what is the difference between clustered and non-
clustered?
Index makes your search faster by using B-Tree structure logic. Clustered and non-clustered indexes are
two types of indexes. In clustered index the leaf node points to the actual data while in non-clustered
index the leaf node uses the clustered index to locate data.
• Function cannot affect the state of the database which means we cannot perform CRUD operation
on the database. Stored Procedure can affect the state of the database by using CRUD operations.
• Store Procedure can return zero or n values whereas Function can return only one value.
• Store Procedure can have input, output parameters for it whereas functions can have only input
parameters.
• Function can be called from Stored Procedure whereas Stored Procedure cannot be called
fromFunction.
• WCF services can be hosted in multiple protocols like http, tcp etc. Web services can only be
hosted on Http protocol.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
• WCF has COM+ so you can call two different WCF services in a transaction , we can not call
two different web services in one transaction.
• WCF integrates with MSMQ easily, but for web services we will need to write code to
communicate with the MSMQ pool.
In simple words below equation shows the difference with simple equation.
Note :- Do watch the below 4 videos of WCF to get more insight in to WCF.
What are basic steps to create a WCF service (Part I, Creating the Service)?
What are basic steps to create a WCF service (Part II, Consuming the
Service)?
What are endpoints, address, contracts and bindings?
What are various ways of hosting WCF service?
When we want to host any WCF service we need to provide where to host it, how to host it and what to
host.
• Contract (What)
Contract is an agreement between two or more parties. It defines the protocol how client should
communicate with your service. Technically, it describes parameters and return values for a method.
• Address (Where)
An Address indicates where we can find this service. Address is a URL, which points to the location of
the service.
• Binding (How)
Bindings determine how the service can be accessed. It determines how communications is done. For
instance, you expose your service, which can be accessed using SOAP over HTTP or BINARY over TCP.
So for each of these communications medium two bindings will be created.
• End point: - It’s the combination of contract, address and binding.
In WCF web.config file we can specify end point , address , binding and contract as shown in the below
code snippet.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Note :- Do watch the below 4 videos of WCF to get more insight in to WCF.
What are basic steps to create a WCF service (Part I, Creating the Service)?
What are basic steps to create a WCF service (Part II, Consuming the
Service)?
What are endpoints, address, contracts and bindings?
What are various ways of hosting WCF service?
What is the difference of hosting a WCF service on IIS and Self hosting?
What is the difference between BasicHttpBinding and WsHttpBinding?
WPF (Windows Presentation foundation) is a graphical subsystem for displaying user interfaces,
documents, images, movies etc. It uses XAML which is a XML descriptive language to
represent UI elements.
Silver light is a web browser plug-in by which we can enable animations, graphics and audio video. You
can compare silver light with flash. We can view animations with flash and it’s installed as a plug-in in
the browser.
Note :- Do have a look at the below videos for WPF and silverlight.
What is the need of WPF when we had GDI, GDI+ and DirectX?
Can you explain how we can make a simple WPF application?
Can you explain the architecture of Silverlight ?
What are the basic things needed to make a silverlight application ?
LINQ is a uniform programming model for any kind of data access. It is also an OR mapper which helps
us to expedite our business object creation process.
ADO.NET entity is an ORM (object relational mapping) which abstracts data model by providing a
simplified object model.
In other words the complete middle tier development is expedited using entity framework.
Note :- Below simple video demonstration in the CD will help your understand
LINQ and entity framework in to great depth.
What is LINQ and can you explain same with example?
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Can you explain a simple example of LINQ to SQL?
• LINQ to SQL is good for rapid development with SQL Server. EF is for enterprise scenarios and
works with SQL server as well as other databases.
• LINQ maps directly to tables. One LINQ entity class maps to one table. EF has a conceptual model
and that conceptual model map to storage model via mappings. So one EF class can map to
multiple tables or one table can map to multiple classes.
• LINQ is more targeted towards rapid development while EF is for enterprise level where the need is
to develop loosely coupled framework.
If you are starting with fresh development using entity framework, in case you are in older version of
framework where entity framework does not exist use linq to sql.
Note :- Do watch the following videos for design pattern which is shipped
with the CD :-
Introduction
Factory pattern
Memento Pattern
Singleton Pattern
Left to the readers, pick any three patterns which you have used in your project and talk about it. In
chapter “Design patterns, UML, Estimation and Project management” we have explained 3 design
patterns.
Note :- In CD we have snipped 3 design pattern videos you can have a look at
them.
Factory pattern
Memento Pattern
Singleton Pattern
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Singleton pattern helps us to create a single instance of an object which can be shared across project.
Main use of singleton pattern is for global data sharing and caching.
Note :- The CD contains a video explanation with source code for “Singleton
Pattern”.
All the above design patterns come in presentation pattern category and help to remove any kind of
cluttered code in UI like manipulation of user interfaces and maintaining state. Thus keeping your UI
code cleaner and better to maintain.
MVC pattern divides the architecture in to 3 part model, view and controller. The first request
comes to the controller and the controller then decides which view to be displayed and ties up the
model with the view accordingly.
MVP (Model view presenter) has the same goals as MVC i.e. separating the UI from the model.
It does the same by using a presenter class. The UI talks via an interface to the presenter class
and the presenter class talks with the model.
MVVM is an architectural pattern with the focus of removing UI cluttered code. It does the same by using
an extra class called as view model. MVVM is mostly suitable for Silverlight and WPF projects because
of the rich bindings provided by the technologies.
Note :- In the CD we have shipped 4 videos which explains MVC , MVP and MVVM
patterns. Below are the name of the videos :-
The basic of MVC HttpHandlers
MVC using core ASP.NET and HttpHandler
MVC using MVC ASP.NET
Model View Presenter video
The Unified Modeling Language (UML) is a graphical language for visualizing, specifying, constructing,
and documenting the artifacts of a software-intensive system.
UML provides blue prints for business process, System function, programming language statements,
database schemas and reusable components.Some of the important UML diagrams are use case , class
diagrams , sequence diagram, activity diagram , object diagrams , collaboration diagrams , state chart
diagrams , component diagram and deployment diagram.
Note :- We have shipped 5 videos which explains some important UML diagrams
in detail. Below is the list.
Introduction
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Use Case Diagrams
Class Digrams
Sequence Digrams
Collaboration Diagrams
• Requirement
• Design
• Coding and unit testing
• System testing
• Acceptance testing
• Go live
Ajax stands for Asynchronous JavaScript and XML. There are two prime benefits of Ajax:-
• It send’s only necessary data to the server. For instance let’s say you have 4 textboxes and on a
submit button you want to only send two text box data, Ajax helps in the same.
• The second benefit is it’s asynchronous. In other words when you click on submit button and until
the server processes the request you can do other activities on the site. For instance when you
click on send email and until the email is sent , you can start composing a new email at the back
ground.
From unit testing perspective there are two great tools “NUNIT” and “Visual studio unit test template”.
Talk about which you are comfortable with. Below are two videos in DVD which shows demo of how to
use NUNIT and VSTS unit test template.
Note :- In the CD we have shipped four videos which explain unit testing
using
What is Unit Testing & can we see an example of the same?
How can we write data driven test using NUNIT & VS Test?
What is Agile?
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Agile is a development methodology where we develop in incremental and iteratively. In agile
weconsider software as the most important entity and accept user changes and deliver them in small
releases. There are four important principle of agile:-
• Individuals and interactions over processes and tools.
• Working software over comprehensive documentation.
• Customer collaboration over contract negotiation.
• Responding to change over following a plan.
Code reviews are either done manually i.e. peer review or automated review using tools like
style cop and fxcop.
Note :- We have shipped two videos in the CD which explains how to use
stylecop and fxcop tools for code reviews.
Requirements are normally available in use cases or free text. The first step is to identify the
classes, properties for the classes, methods / functions and relationship between the classes.
As a general rule nouns become classes and verbs become actions for the classes.
Once the classes are identified we can use sequence or collaboration diagrams to detail out the
interactions.
The database objects are later created using the class diagrams.
Note: - Half compiled means this code is not yet compiled to machine/CPU
specific instructions.
We do not know in what kind of environment.NET code will run. In other words we do not know what
can be the end operating system, CPU configuration, machine configuration, security configuration etc.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
So the IL code is half compiled and on runtime this code is compiled to machine specific using the
environmental properties (CPU,OS, machine configuration etc).
JIT compiles the code just before execution and then saves this translation in memory. Just before
execution JIT can compile per-file, per function or a code fragment.
Ngen storesfull compiled.NET native code in to cache. In other words rather than dynamically compiling
the code on run time a full image of native compiled code is stored in cache while installing the
application. This leads to better performance as the assembly loads and execute faster.
In order to install full compiled native code in cache we can execute the below command line from your
visual studio command prompt.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
So does it mean that NGEN.EXE will always improve performance?
No, it’s not always necessary that ngen.exe produces optimized code because it uses the current
environments parameters which can change over a period of time. For instance a code compiled in
windows XP environment will not be the optimized code to run under windows 2008 server. So we need
to once test with ‘ngen’ and without ‘ngen’ to conclude if really the performance increases.
Yes by using ILDASM simple tool we can view a IL code of a DLL or EXE. In order to view IL code
using ILDASM , go to visual studio command prompt and run “ILDASM.EXE”. Once ILDASM is
running you view the IL code.
What is a CLR?
CLR (Common language run time) is the heart of.NET framework and it does 4 primary important
things:-
• Garbage collection
• CAS (Code Access security)
• CV (Code verification)
• IL to Native translation.
Note: - There are many other uses of CLR but I have kept it short from the
interview point of view. In the further section we will go in depth of these
questions.
Code that executes under CLR execution environment is called as managed code. Unmanaged code
executes outside CLR boundary. Unmanaged code is nothing but code written in C++ , VB6 , VC++ etc.
Unmanaged codes have their own environment in which the code runs and it’s completely outside the
control of CLR.
Garbage collector is a feature of CLR which cleans unused managed (it does not clean unmanaged
objects) objects and reclaims memory. It’s a back ground thread which runs continuously and at specific
intervals it checks if there are any unused objects whose memory can be claimed.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Note: - Garbage collector is one of the very important interview topics due
to complexity of generations, double GC loop because of destructor and the
implementation of finalize and dispose pattern. So please do go through the
video of “What is Garbage collection, Generation, Finalize, Dispose and
Idisposable?” to ensure that you understand the fundamentals well.
Garbage collector only claims managed code memory. For unmanaged code you need to put clean up in
destructor / finalize.
Yes, when we define a destructor, garbage collector does not collect these objects in the first round. It
moves them to Gen 1 and then reclaims these objects in the next cycle.
As more objects are created in Gen 1 the performance of the application falls down because more
memory is consumed.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
class clsMyClass : IDisposable
{
~clsMyClass()
{
// In case the client forgets to call
// Dispose , destructor will be invoked for
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// Free managed objects.
}
// Free unmanaged objects
}
“System.GC.Collect ()” forces garbage collector to run. This is not a recommendedpractice but can be
used if situations arise.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
• Finalize is a destructor and dispose is a function which is implemented via ‘Idisposable’ interface.
• Finalize is nondeterministic, since it’s called by garbage collector. Dispose is a function and needs
to be called by the client for clean up. In other finalize is automatically called by garbage
collector while dispose needs to be called forcefully.
Note: -As a good practice Finalize and dispose is used collectively because
of double garbage collector loop. You can talk about this small note after
you talk about the above 2 differences.
What is CTS?
In .NET there are lots of languages like C#, VB.NET, VF.NET etc. There can be situations when we
want code in one language to be called in other language. In order to ensure smooth communication
between these languages the most important thing is that they should have a common type system. CTS
(Common types system) ensures that data types defined in two different languages get compiled to a
common data type.
So “Integer” data type in VB6 and “int” data type in C++ will be converted to System.int32, which is data
type of CTS.
Note: If you know COM programming, you would know how difficult it is to
interface VB6 application with VC++ application. As datatype of both
languages did not have a common ground where they can come and interface, by
having CTS interfacing is smooth.
CLS is a subset of CTS. CLS is a specification or set of rules or guidelines. When any programming
language adheres to these set of rules it can be consumed by any .NET language.
For instance one of the rule which makes your application CLS non-compliant is when you declare your
methods members with same name and with only case differences in C#. You can try this create a simple
class in C# with same name with only case differences and try to consume the same in VB.NET ,it will
not work.
What is an Assembly?
There are two types of assembly Private and Public assembly. A private assembly is normally used by a
single application, and is stored in the application's directory, or a sub-directory beneath. A shared
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
assembly is stored in the global assembly cache, which is a repository of assemblies maintained by the
.NET runtime.
Shared assemblies are needed when we want the same assembly to be shared by various applications in
the same computer.
What is Namespace?
What is ILDASM?
ILDASM is a simple tool which helps you to view IL code of a DLL or EXE. In order to view IL code
using ILDASM , go to visual studio command prompt and run “ILDASM.EXE”. Once ILDASM is
running you view the IL code.
What is Manifest?
Assembly metadata is stored in Manifest. Manifest contains metadata which describes the following
things -:
• Version of assembly.
• Security identity.
• Scope of the assembly.
• Resolve references to resources and classes.
The assembly manifest is stored in the DLL itself.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Is versioning applicable to private assemblies?
Yes, versioning is applicable to private assemblies also.
Note:- This question can also be asked in two different ways , what are
weak references and strong reference or how do you strong name a .NET
assembly.
When we talk about .NET application it has two parts one is the class library or the DLL and the other the
consumer like windows UI etc using this DLL.
If the consumer identifies the DLL library by namespace and class names it’s called as weak reference.
It’s very much possible in deployment environment someone can delete the original class library and fake
a similar class library with the same class name and namespace name.
Strong name is a unique name which is produced by the combination of version number, culture
information,public key and digital signature. No one can fake this identity or generate the same name.
So your consumer or UI will refer the class library with strong names rather than class and namespace
names. In order to create strong name, right click on the class library, click on properties, click on signing
tab and click on the new menu to generate strong names as shown in the below figure.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
What is Delay signing?
The whole point about strong names is to ensure that the clients (UI , External components etc) who is
consuming the DLL knows that the DLL was published from a valid source. This authenticity is verified
by using strong names. Strong name protection is good from external hackers but what if your own
developers think of doing something mischievous.
That’s where delay signing helps. The strong name key has two keys public key and private key. You
only share the public key with your developers so that they can work seamlessly. The private key is stored
in a secured location and when the DLL is about to be deployed on production the key is injected for
further security.
What is GAC?
GAC (Global Assembly Cache) is where all shared .NET assembly resides. GAC is used in the following
situations:-
• If the application has to be shared among several applicationwhich is in the same computer.
• If the assembly has some special security, requirements like only administrators can remove
the assembly. If the assembly is private then a simple delete of assembly the assembly file
will remove the assembly.
You can use the ‘GacUtil’ tool which comes with visual studio. So to register an assembly in to GAC go
to “Visual Studio Command Prompt” and type “gacutil –i (assembly name)”, where (assembly name) is
the DLL name of the project.
One you have installed the assembly the DLL can be seen in ‘c:\windows\assembly\’ folder.
When we have many DLL’s to be deployed we need to create setup and deployment package using
windows installer. So the common way of deploying GAC DLL in production is by using windows
installer.
When we have two version of the same assembly in GAC we need to use binding redirect tag and specify
the version we want to use in the new version property as shown in the below “app.config” file.
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
http://www.questpond.com
For more ma
aterials on
o .NET, mail
m us questpond
q d@questp
pond.com
m
Call on +91-22-667552917 / +91-99675907077
<assembl
lyIdentity
y name="Com
mputerName
e" publicKe
eyToken="c
cfc68d722cd
d6a164" />
>
<publish
herPolicy apply="yes
s" />
<binding
gRedirect oldVersion
n="1.1.0.0
0" newVersi
ion="1.0.0
0.0" />
</depend
dentAssemb
bly>
</assemb
blyBinding
g>
</runtim
me>
</config
guration>
What is
s Reflectio
on and wh
hy we nee
ed it?
How do
o we imple
ement refflection?
h
http://www
w.questpo
ond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
to System.Reflection namespace) class to get a reference to the type of the object. Later we can
use “Activator.CreateInstance” to create an instance of the class. The “GetType()” function helps
us to get reference to the type of the object.
var myAssembly = Assembly.LoadFile(@"C:\ClassLibrary1.dll");
var myType = myAssembly.GetType("ClassLibrary1.Class1");
dynamic objMyClass = Activator.CreateInstance(myType);
// Get the class type
Type parameterType = objMyClass.GetType();
Step 2 :- Once we have reference the type of the object we can then call “GetMembers” or
“GetProperties” to browse throw the methods and properties of the class.
// Browse through members
foreach (MemberInfo objMemberInfo in parameterType.GetMembers())
{Console.WriteLine(objMemberInfo.Name);}
In case you want to invoke the member which you have inspected you can use “InvokeMember”
to invoke the method. Below is the code for the same.
parameterType.InvokeMember("Display",BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.InvokeMethod |
BindingFlags.Instance,null, objMyClass, null);
• If you are creating application like visual studio editors where you want show internal of
an object by using intellisense.
• In unit testing sometimes we need to invoke private methods. That’s a different thing test
private members are proper or not.
• Sometimes we would like to dump properties, methods and assembly references to a file
or probably show it on a screen.
Programming languages can be divided in to two categories strongly typed and dynamically
typed. Strongly typed languages are those where the checks happen during compile time while
dynamic languages are those where type checks are bypassed during compile time. In dynamic
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
language object types are known only during runtime and type checks are activated only at run
time.
So we would like to take advantage of both the world. Because many times we do not know
object type until the code is executed. In other words we are looking at something like
dynamically statically typed kind of environment. That’s what dynamic keyword helps us with.
If you create a variable using the “Dynamic” keyword and if you try to see members of that
object you will get a message as shown below “will be resolved at runtime”.
Now try the below code out. In the below code I have created a dynamic variable which is
initialized with a string data. And in the second line I am trying to have fun by trying to execute
a numeric incremental operation. So what will happen now ?.... think.
dynamic x = "c#";
x++;
Now this code will compile fine without any complains. But during runtime it will throw an
exception complaining that the mathematical operations cannot be executed on the variable as
it’s a string type. In other words during runtime the dynamic object gets transformed from
general data type to specific data type (ex: - string for the below code).
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
One of the biggest practical uses of dynamic keyword is when we operate on MS office
components via interop.
So for example if we are accessing Microsoft excel components without dynamic keyword , you
can see how complicated the below code is. Lots of casting happening in the below code, right.
// Before the introduction of dynamic.
Application excelApplication = new Application();
((Excel.Range)excelApp.Cells[1, 1]).Value2 = "Name";
Excel.Range range2008 = (Excel.Range)excelApp.Cells[1, 1];
Now look at how simple the code becomes by using the dynamic keyword. No casting needed
and during runtime type checking also happens.
// After the introduction of dynamic, the access to the Value property and
// the conversion to Excel.Range are handled by the run-time COM binder.
dynamic excelApp = new Application();
excelApp.Cells[1, 1].Value = "Name";
Excel.Range range2010 = excelApp.Cells[1, 1];
• Both reflection and dynamic are used when we want to operate on an object during
runtime.
• Reflection is used to inspect meta-data of an object. It also has the ability to invoke
members of an object on runtime.
• Dynamic is a keyword which was introduced in .NET 4.0. It evaluates object calls during
runtime. So until the method calls are made compiler is least bothered if those methods /
properties etc exist or not.
http://www.questpond.com
For more ma
aterials on
o .NET, mail
m us questpond
q d@questp
pond.com
m
Call on +91-22-667552917 / +91-99675907077
• Dynamic uses reflection internally.
D i Itt caches the method
m callss made thus improving
performance to a certain extent.
e
• R
Reflection caan invoke botth public andd private meembers of ann object whille dynamic can
c
onnly invoke public
p membbers.
For instaance when th he below codde run the firrst two variabbles i.e. “i” and
a “y” are stored in a stack
s
and the laast variable “o” is storedd in heap.
void MyF
Function()
{
int i = 1; // Thi
is is store
ed in stac
ck.
int y = i; // Thi
is is store
ed in stac
ck.
object o = null; // This is
s stored in
i heap.
h
http://www
w.questpo
ond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
} // after this end the stack variable memory space is reclaimed while //
the heap memory is reclaimed later by garbage collector.
Value types contain actual data while reference types contain pointers and the pointers point to the actual
data.
Value types are stored on stack while reference types are stored on heap. Value types are your normal
data types like int , bool , double and reference types are all objects.
When value type is moved to a reference type it’s called as boxing. The vice-versa is termed as
unboxing.
Below is sample code of boxing and unboxing where integer data type is converted in to object and then
vice versa.
int i = 1;
object obj = i; // boxing
int j = (int) obj; // unboxing
When boxing and unboxing happens the data needs to jump from stack memory to heap and
vice-versa which is a bit of memory intensive process. As a good practice avoid boxing and
unboxing where ever possible.
First thing it’s very difficult to avoid boxing and unboxing. For instance most of the time you
will moving data from UI objects like text boxes etc to business objects and also vice versa
which will demand boxing and unboxing. Below are some key points to remember:-
• First thing is it really necessary to use boxing and unboxing. If it’s unavoidable like
moving data from UI text boxes to internal c# data types, then go for it.
• Try to see if you can use generics and avoid it.
By design, .NET embeds rich Meta data inside the executable code using MSIL. Any one can easily
decompile your DLL back using tools like ILDASM (owned by Microsoft) or Reflector for .NET whichis
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
a third party. Secondly, there are many third party tools, which make this decompiling process a click
away. So any one can easily look in to your assemblies and reverse engineer them back in to actual source
code and understand some real good logic, which can make it easy to crack your application.
The process by which you can stop this reverse engineering is using “obfuscation”. It is a technique,
which will foil the decompilers. Many third parties (XenoCode, Demeanor for .NET) provide .NET
obfuscation solution. Microsoft includes one that is Dotfuscator Community Edition with Visual
Studio.NET.
Just to give an understanding of what the above question means seethe below code.
int i =0;
MessageBox.Show(i.ToString());
MessageBox.Show(Convert.ToString(i));
We can convert the integer “i” using “i.ToString()” or “Convert.ToString” so what is the difference. The
basic difference between them is “Convert” function handles NULLS while “i.ToString()” does not.It will
throw a NULL reference exception error. So as a good coding practice using “convert” is always safe.
Once the exception is raised if you want to catch the same you need to use the try catch block as shown
below.
try
{
// This section will have the code which
// which can throw exceptions.
}
catch(Exception e)
{
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
// Handle what you want to
// do with the exception
label.text = e.Message;
}
If you do not catch the error, .NET framework will handle the same and you will get a message box as
shown in the below figure.
Exceptions that are thrown by .NET framework are called as system exceptions. These errors are non-
recoverable or fatal errors like ArgumentOutOfRangeException, IndexOutOfRangeException,
StackOverflowException etc.
Application exceptions are custom exceptions created for the application. Application exceptions are
created by deriving from “ApplicationException” class as shown below. You can then create the object of
the below exception and throw the same from the code and catch the same on the client side.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
public class MyOwnException : ApplicationException
{
private string messageDetails = String.Empty;
public DateTime ErrorTimeStamp {get; set;}
public string CauseOfError {get; set;}
public MyOwnException(){}
public MyOwnException(string message,
string cause, DateTime time)
{
messageDetails = message;
CauseOfError = cause;
ErrorTimeStamp = time;
}
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Are Arraylist faster or Arrays?
Array list takes any data type which leads to boxing and unboxing. As arrays are strongly typed they do
not do boxing and unboxing. So arrays are faster as compared to array list.
// Array definition
int[] str = new int[10];
Hash table helps to locate data using keys as shown below. When we add data to hash table it also has a
provision where we can add key with the data. This key will help us to fetch data later using key rather
than using internal index id’s generated by collections.
objHashtable.Add(“p001”,”MyData”);
This key is converted in to numeric hash value which is mapped with the key for quick lookup.
Queues are collection which helps us to add object and retrieve them in the manner they were added. In
other word queues helps us to achieve the first in first out collection behavior.
Stack collection helps us to achieve first in last out behavior.
Generics help to separate logic and data type to increase reusability. In other words you can create a class
whose data type can be defined on run time.
For instance below is a simple class “class1” with a “compareme” function created using generics. You
can see how the unknown data type is put in greater than and less than symbol. Even the compare me
method has the unknown data type attached.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
if (v1.Equals(v2))
{
return true;
}
else
{
return false;
}
}
}
During runtime you can define the datatype as shown in the below code snippet.
Array List, Stack and Queues provide collections which are not type safe. This leads 2 problems first it’s
not type safe and second it leads to boxing and unboxing.
By using generics we can have type safety and also we can avoid boxing and unboxing. Below is a simple
code snippet which shows a strong typed list of type integer and string.
List<int> obj;
obj.add(1); // you can only add integers to this list
List<string> obj;
obj.add(“shiv”); // you can only add string to this list
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
What is the difference between dictionary and hashtable?
Dictionary collection is a generic collection equivalent for hashtable. Hashtable allows you to add key
and value of any type (i.e. objects) . This leads to two problems one is boxing and unboxing issues and
second it’s not strongly typed.
// Creates a strongly typed dictionary with integer key and value
// pair
Dictionary<int,int> obj = new Dictionary<int,int>();
// We can only add integer value and key to the dictionary collection
Obj.Add(123,550);
What are the generic equivalent for array list,stack, queues and hashtable?
Below are the listed generic equivalents for each of them:-
• Array list generic equivalent is List<int>.
• Stack generic equivalent is Stack<int>.
• Queue generic equivalent is Queue<int>.
• Hashtable generic equivalent is Dictionary<int,int>.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
CAS is the part of .NET security model which determines whether or not a particular code is allowed to
run and what kind of resources can the code access.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
CAS is deprecated in .NET 4.0 and two major changes are brought in:-
• Permission granting is no more the work of CAS; it’s now the work of the hosting model. In other
words CAS is disabled in .NET 4.0 by default. The host will decide what rights to be given to the
.NET assembly.
• A new security model i.e. Security transparent model is introduced. The security transparent model
puts code in to separate compartments/ boxes as per the risk associated. If you know a code can
do something wrong you can compartmentalizethe code as ‘Security transparent’ and if you have
a code which you trust you can box them in to ‘Security critical’.
What is sandboxing?
If you have want to execute an untrusted third party DLL, you can create your own ‘appdomain’
and assign permission sets so that your 3rd party DLL runs under a control environment.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
How can we create a windows service using .NET?
Windows Services are long-running processes that runs at the background.It has the ability to start
automatically when the computer boots and also can be manually paused, stopped or even restarted.
Following are the steps to create a service:-
Create a project of type “Windows Service”.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
}
Now to install the service you need to do run the install util exe.
Serialization is a process where we can convert an object state in to stream of bytes. This stream
can then be persisted in a file,database, or sent over a network etc. Deserialization is just vice-
versa of serialization where we convert stream of bytes back to the original object.
// Serialization
Customer obj = new Customer(); // Create object
obj.CustomerCode = 123; // Set some values
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
// De-Serialization
IFormatter formatter = new BinaryFormatter(); // Use binary formatter
Stream stream = new FileStream("MyFile.txt", FileMode.Open, FileAccess.Read,
FileShare.Read); // read the file
If you want to save to XML or any other content type use the appropriate formatter.
• Binary is smaller in size, so faster to send across network and also faster to process.
• XML is more verbose, but easy to understand and human readable. But due to the XMLstructure
its complex to parse and can impact performance.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Note :- Many people answer that XML serialization should be used when you
have different platforms and binary serialization should be used when you
same platforms. But this answer is actually not right as we have lot of
binary serialization methodology like ASN , protbuf which are cross platform
and widely accepted. So the important difference is that one is XML which
readable by eyes and the binary is not.
Short circuiting occurs when you do logical operations like ‘AND’ and ‘OR’.
“When we use short circuit operators only necessary evaluation is done rather than full evaluation.”
Let us try to understand the above sentence with a proper example. Consider a simple “AND” condition
code as shown below. Please note we have only one “&” operator in the below code.
In the above case “Condition2” will be evaluated even if “Condition1” is “false”. Now if you think
logically, it does not make sense to evaluate “Condition 2”, if “Condition 1” is false .It’s a AND condition
right? , so if the first condition is false it means the complete AND condition is false and it makes no
sense to evaluate “Condition2”.
There’s where we can use short circuit operator “&&”. For the below code “Condition 2” will be
evaluated only when “Condition 1” is true.
if(Condition1 | Condition2)
{
}
So if we change the same to double pipe (“||”) i.e. implement short circuit operators as shown in the below
code, “Condition2” will be evaluated only if “Condition1” is “false”.
if(Condition1 || Condition2)
{
}
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
What is the difference between “Typeof” and “GetType” ?
Both “TypeOf” and “GetType” help you to get the type. The difference is from where the information is
extracted. “TypeOf” gets the type from a class while “GetType” gets type from an object.
No, the above code will give an error. Double size is larger than “int” so an implicit conversion will not
take place. For that we need to do explicit conversion. So we need to something as shown in the below
code. In the below code we have done an explicit conversion.
Also note after explicit conversion we will have data loss. In variable “i” we will get “109” value , the
decimal values will be eliminated.
“IComparable” interface helps to implement custom sorting for collections in c#. Let us try to
understand the same with a simple c# example. For instance let’s say you have a list collection of
people names as shown in the below code.
Now if you run the above program you will see that we have not applied sort on the collection. It
displays data as they were inserted.
Shiv
Raju
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Sukesh
Ajay
But now if you call “Peoples.Sort()” method on the collection you will get the following sorted
output on the “name” value in ascending position.
Ajay
Raju
Shiv
Sukesh
But now let’s say that we need the person’s age also to be added in the list with the person name
value. So logically you will create a “Person” class with “name” and “age” property as shown in
the code below.
class Person
{
private string _Name;
Once you create the class you would create an object of the person class and add it to the list
collection as shown in the below code snippet.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
class Program
{
static void Main(string[] args)
{
List<Person> Peoples = new List<Person>();
Peoples.Add(Createperson("Shiv",20));
Peoples.Add(Createperson("Raju", 20));
Peoples.Add(Createperson("Sukesh", 30));
Peoples.Add(Createperson("Ajay", 40));
Peoples.Sort();
foreach (Person obj in Peoples)
{
Console.WriteLine(obj.Name + " " + obj.Age);
}
}
static Person Createperson(string Name, int Age)
{
Person obj = new Person();
obj.Name = Name;
obj.Age = Age;
return obj;
}
}
But if you now try to call the “Sort” method on the List , he gets confused ?. On which value
should he sort on “Name” or “Age” ?.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
If you run the application it will throw up the below exception text. The exception text says that
he is confused and he needs specific direction on how the sorting should work. This direction can
be provided by using “IComparable” interface.
So in order to show a proper direction for the sort logic we need to implement “IComparable”
interface as shown in the below. The logic of “Sort” needs to be defined in the “CompareTo”
method.
if (other.Age == this.Age)
{
return this.Name.CompareTo(other.Name);
}
else
{
return other.Age.CompareTo(this.Age);
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
}}}
You can see in the “CompareTo” method we have defined the logic saying if the “age” value is
same then sort by using the “name” value or else use “age” value for sorting. If you run the
application you would get the following output. You can see for “40” and “30” value he has
sorted on the basis “Age” but for the remaining people the age is same so he sorted on the
“Name” value.
Loki 40
Sukesh 30
Ajay 20
Madan 20
Raju 20
Shiv 20
“IComparable” interface helps you to implement a default sort implementation for the collection.
But what if we want to sort using multiple criteria’s?.For those instances “IComparable” has a
limitation and “IComparer” is the guy.
For example if we want to sort the list by “Name” under some situation or sort by “Age” under
some other situations we need to implement “IComparer” interface.
So the first step is to create different classes for each sort criteria. These classes will implement
“IComparer” interface and will have sorting logic defined in the “Compare” method. You can
see we have two different classes defined “CompareByName” and “CompareByAge”. One
compares on the basis of “name” and the other on the basis of “age”.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
}
class CompareByAge : IComparer<Person>
{
public int Compare(Person x, Person y)
{
if (x.Age > y.Age) return 1;
if (x.Age < y.Age) return -1;
return 0;
}
}
If you see the logic for “CompareByName” its simple. It uses the string comparison to evaluate
the “Name” value sorting. But when we talk about numeric comparison there are 3 possible
outputs Greater than , less than or Equal. So if you see “CompareByAge” class it returns 3 values
1 ( Greater than) , -1 ( Less than ) and 0 ( for Equal to).
Now that we have created the separate logics we can now invoke the “Peoples’ list by passing
the class object. So for example if we want to sort by name, you will use the below code snippet.
Peoples.Sort(new CompareByName());
The output of the above code is nothing but alphabetically sorted data.
Ajay 20
Loki 40
Madan 20
Raju 20
Shiv 20
Sukesh 30
If you invoke the sort method of the list by using the age logic it will throw an output sorted on
age value.
Peoples.Sort(new CompareByAge());
Ajay 20
Raju 20
Shiv 20
Madan 20
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Sukesh 30
Loki 40
Lazy loading is a concept where we delay the loading of the object unit the point where we need
it. Putting in simple words on demand object loading rather than loading the objects
unnecessarily.
For example consider the below example where we have a simple “Customer” class and this
“Customer” class has many “Order” objects inside it. Have a close look at the constructor of the
“Customer” class. When the “Customer” object is created it also loads the “Order” object at that
moment. So even if we need or do not need the address object , it’s still loaded.
But how about just loading the “Customer” object initiallyand then on demand basis load the
“Order” object.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
public class Customer
{
private List<Order> _Orders= null;
…
…
public Customer()
{
_CustomerName = "Shiv";
_Orders = LoadOrders(); // Loads the address object even though
//not needed
}
So let’s consider you have client code which consumes the “Customer” class as shown below. So
when the “Customer” object is created no “Order” objects should be loaded at that moment. But
as soon as the “foreach” loop runs you would like to load the “Order” object at that point ( on
demand object loading).
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
}
So for the above example if we want to implement Lazy loading we will need to make the
following changes:-
Now if you run the client code and halt your debugger just before the “ForEach” loop runs over
the “Orders”object, you can see the “Orders” object is null ( i.e. not loaded). But as soon as the
“ForEach” loop runs over the “Order” object it creates the “Order” object collection.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Are there any readymade objects in .NET by which we can implement Lazy
loading?
In .NET we have “Lazy<T>” class which provides automatic support for lazy loading. So let’s
say if you want to implement “Lazy<>” in the above code we need to implement two steps for
the same:-
Attach this Lazy<> object with the method which will help us load the order’s data.
Now as soon as any client makes a call to the “_Orders” object, It will call the “LoadOrders”
function to load the data.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Below goes the full code for the same.
}
public Customer()
{
// Makes a database trip
_CustomerName = "Shiv";
_Orders = new Lazy<List<Order>>(() => LoadOrders());
}
}
The disadvantage is that the code becomes complicated. As we need to do checks if the loading
is needed or not. So must be there is a slight decrease in performance.
http://www.questpond.com
For more ma
aterials on
o .NET, mail
m us questpond
q d@questp
pond.com
m
Call on +91-22-667552917 / +91-99675907077
Now let mem complicaate this situaation let’s sayy the caller only
o wants values
v greateer than “3” from
fr
the collecction. So thee obvious thhing as a c# developer
d we will do is create
c a funcction as show
wn
h
http://www
w.questpo
ond.com
For more ma
aterials on
o .NET, mail
m us questpond
q d@questp
pond.com
m
Call on +91-22-667552917 / +91-99675907077
below. This
T function n will have teemporary collection. In this
t temporary collectionn we will firsst
add valuees which aree greater thann “3” and retturn the sam
me to the caller. The calleer can then
iterate through this co
ollection.
staticIEn
numerable<in
nt> FilterWi
ithoutYield()
{
List<int>
> temp = new
wList<int>()
);
foreach (
(int i in My
yList)
{
if (i > 3
3)
{
temp.Add(i)
);
}
}
return te
emp;
}
h
http://www
w.questpo
ond.com
For more ma
aterials on
o .NET, mail
m us questpond
q d@questp
pond.com
m
Call on +91-22-667552917 / +91-99675907077
• Step 3:- Calleer displays thhe value on the
t console anda re-enters the functioon for more data.
d
This time when it reenters, it does not start from first.
T f It remeembers the sttate and startts
frrom “5”. Thee iteration coontinues furtther as usuall.
In other words
w we woould like to iterate
i throuugh the collecction and as we iterate would
w like too
maintain running totaal state and return
r the vaalue to the caaller ( i.e. coonsole appliccation). So thhe
function now becomees somethingg as shown below. b The “runningtota
“ al” variable will
w have thee old
value eveery time the caller re-entters the function.
staticIEn
numerable<in
nt> RunningT
Total()
{
int runni
ingtotal=0;
h
http://www
w.questpo
ond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
int index=0;
foreach(int i in MyList)
{
index = index + 1;
if(index==1)
{
runningtotal = i;
}
else
{
runningtotal = i + runningtotal;
}
yieldreturn (runningtotal);
}
}
Below goes the caller code and output.
foreach (int i in RunningTotal())
{
Console.WriteLine(i);
}
Console.ReadLine();
When we create any object there are two parts to the object one is the content and the other is
reference to that content.
So for example if you create an object as shown in below code:-
1. “.NET interview questions” is the content.
2. “o” is the reference to that content.
object o = ".NET Interview questions";
http://www.questpond.com
For more ma
aterials on
o .NET, mail
m us questpond
q d@questp
pond.com
m
Call on +91-22-667552917 / +91-99675907077
“==” com mpares if thee object refeerences are same while “.Equals()”
“ c
compares if the
t contents are
same.
So if youu run the belo
ow code botth “==” and “.Equals()” returns
r true because conntent as well as
referencees are same.
object o
= ".NET Int
terview ques
stions";
object o1
1 = o;
Console.W
WriteLine(o
== o1);
Console.W
WriteLine(o.
.Equals(o1));
Console.R
ReadLine();
True
True
Now connsider the bellow code whhere we havee same conteent but they point towardds different
instancess. So if you run
r the below
w code both “==” will return
r false and “.Equalss()” will retturn
true.
object o
= ".NET Int
terview ques
stions";
object o1
1 = newstrin
ng(".NET Int
terview questions".ToCharArray());
Console.W
WriteLine(o
== o1);
Console.W
WriteLine(o.
.Equals(o1));
Console.R
ReadLine();
h
http://www
w.questpo
ond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
False
True
When you are using string data type it always does content comparison. In other words you
either use “.Equals()” or “==” it always do content comparison.
What’s the difference between catch with parameter and catch without
parameter?
catch(Exception e)
{
…
}
VS
Catch
{
…
}
For this interview question many people answer, “Second one will cause compile error”. But
both the codes will work properly. Actually from .NET 2.0 there is no difference. But in the
initial versions of .NET i.e. prior 2.0 some of the exceptions thrown by some COM components
did not translate to “Exception” compatible object.
From .NET 2.0 both code will execute properly and there is no difference between them
internally. Both catches will handle all kind of exceptions.
After 2.0 a catch which does have any code written in it gives a warning as shown below. So
many developers mark this as a difference.
But you can always overcome this issue by not putting a variable as shown in the below code.
catch (Exception)
{
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
}
How can we mark a method as deprecated?
Many times you want to warn developers that some methods or classes should not be used as
they are either replaced or going to be replaced with new versions. This is possible by using the
“[Obsolete]” attribute.
In the below class we have a method called as “Method1”. Now let’s say you have created a
better improvised version of “Method1” called as “NewMethod1”. You want to send an alert to
all your developers who are consuming this class to use “NewMethod1” rather than using
“Method1”.
So you can decorate “Method1” with the “[Obsolete]” attribute as shown in the below code.
publicclassClass1
{
[Obsolete]
publicvoid Method1()
{
}
publicvoid NewMethod1()
{
}
}
Now if any programmer consumes the above class he will get a warning message as shown in the
below figure.
In case you want to show some message to the developers you can pass the message in the
“Obsolete” attribute as shown in the below code snippet.
[Obsolete("Please use NewMethod1")]
publicvoid Method1()
{
}
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
If you want to be bit strict and do not developers to use that method, you can pass ‘true” to the
“Obsolete” attribute as shown in the below code.
[Obsolete("Please use NewMethod1",true)]
publicvoid Method1()
{
}
Now in case developers try to make a call to “Method1” they will get error and not just a simple
warning.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Build solution menu: - This will perform an incremental build. In other words it will only build
code files which have changed. If they have not changed those files will not touched.
Rebuild solution menu: - This will delete all current compiled files (i.e. exe and dll’s) and will
build everything from scratch, irrespective if there is code change in the file or not.
Clean solution menu: - This menu will delete all compiled files (i.e. EXE’s and DLL’s) from
“bin” / “obj” directory.
Now if you read the above 3 points I have discussed you can conclude that:-
Rebuild = Clean + Build
So the next question would be If you do a “Rebuild” and if you do “Clean” + “Build” , what is
the difference ?.
The difference is the way the build and clean sequence happens for every project. Let’s say if
your solution has two projects “proj1” and “proj2”. If you do a rebuild it will take “proj1” , clean
( delete) the compiled files for “proj1” and build it. After that it will take the second project
“proj2” , clean compiled files for “proj2” and compile “proj2”.
But if you do a “clean” and build”. It will first delete all compiled files for “proj1” and “proj2”
and then it will build “proj1” first followed by “proj2”.
Below image explains the same in a more visual format.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
i++ :- In this scenario first the value is assigned and then increment happens. In the below code
snippet first the value of “i” is assigned to “j” and then “i” is incremented.
++i :- In this scenario first the increment is done and then value is assigned.In the below code
snippet value of “j” is 2 and value of “i” is also 2.
If you visualize in a pictorial manner below is how it looks like. So i++ is a post fix , it first
assigns and then increments. While ++i is a prefix, it first increments and then assigns the value.
http://www.questpond.com
For more ma
aterials on
o .NET, mail
m us questpond
q d@questp
pond.com
m
Call on +91-22-667552917 / +91-99675907077
while (i<5
5) //evaluate
es conditional
l statement
{
//some log
gic
++i;
//increm
ments i
}
while(i++<
<5)//evaluates
s conditional
statement wit
th i value bef
fore increment
t
{
//some log
gic
}
int i =0;
int[]MyAr rray=newint[2];
[
MyArray[i++]=1234;//sets array at index 0 to '1234' and i is incremented
MyArray[i]=5678;//sets array at index 1 to '5678'
int temp =MyArray[‐‐ii];//temp is 11234
public int
i Add(in
nt num1, in
nt num2)
{
return num1
n + num
m2;
}
public int
i Add(in
nt num1, in
nt num2)
{
Co
ontract.Re
equires((nu
um1 > 0) &&
& (num2 > 0)); // preconditio
p on
h
http://www
w.questpo
ond.com
For more ma
aterials on
o .NET, mail
m us questpond
q d@questp
pond.com
m
Call on +91-22-667552917 / +91-99675907077
Co
ontract.En
nsures(Cont
tract.Resu
ult<int>() > 0); // post condi
ition
re
eturn num1
1 + num2;
}
So if you try to call thee “Add” methhod with zero values you shhould get a coontract excepttion error as
shown in the below fig gure.
h
http://www
w.questpo
ond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
No, code contract is not part of visual studio it’s a separate setup. Once you install this setup it creates a
separate tab in “project properties” as shown below. You can then enable static and dynamic checking by
clicking on the below check boxes as shown in the below figure.
Chapter 3: OOP
Note :- We have come out with a exclusive book on ‘OOP’s with real project
scenarios’. In this book we have tried to understand OOP’s fundamentals and
also tried to apply them on projects by simulating project scenarios.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
What is Object Oriented Programming?
OOP is software designing technique where we think in terms of real world objects.
Class is a blue print / template. Objects are instances of classes, in other words they bring life in class. To
use a class we need to create an object.
Abstraction means show only what is necessary. Example color is abstracted to RGB. By just making the
combination of these three colors we can achieve any color in world. So rather than remembering each
and every color we just use RGB.
Encapsulation
It is a process of hiding all the complex processing from the outside world and make’s your objects
simple.
Inheritance
It’s a property of object to act differently under different conditions. For instance a simple user
object depending on conditions can act like a admin or like data entry object.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
• Protected friend (protected internal in C#):- All members in current project and all members in
derived class can access the variables.
• Public: -All members have access in all classes and projects.
Note :- This question can also be tweaked by asking what are the different
access modfiers in .NET .
Below is a simple code snippet where we have “Customer” class which is the parent class. We
have then created a child class called as “CustomerDiscount” which inherits all the properties
and adds a “Discount” property.
class Customer
{
public string customerName;
public string customerCode;
}
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
What are the two different types of polymorphism?
There are 2 kinds of polymorphism static and dynamic. Many people also call them as runtime or
compile time polymorphism.
Below is a simple code snippet which has three classes, Customer class is the parent
class.CustomerDiscount10Percent and CustomerDiscount20Percent are child classes.
Customer parent class has a discount function which returns zero discounts. This function is
defined as virtual and then overridden by both the child classes with 10 and 20% discount.
class Customer
{
public string customerName;
public string customerCode;
public virtual int Discount()
{
return 0;
}
}
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
{
public override int Discount()
{
return 10;
}
Now on the client side on the fly your parent object can point to any child classes and invoke the
child implementation accordingly. This is called as dynamic polymorphism; the parent object
can point to any of the child objects and invoke the child function dynamically.
Customer obj;
obj = new CustomerDiscount10Percent();
obj = new CustomerDiscount20Percent();
Note: - I am not sure why this question is asked frequently. It’s like
comparing apples with mangoes. Probably it’s just the common word “over”
which confuses developers.
Overloading is a concept where we can have same method names with different input signature.
In overriding we have a parent class with virtual functions which are overridden in the child
classes.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
What is operator overloading?
Operator overloading is a concept of polymorphism where you can redefine operators like +, - , *
etc with additional functionalities.
For instance we can redefine the + functionalities to add objects like obj1 + obj2. Below is
simple code snippet which redefines + operator.
class SomeClass
{
You can now use the + operator to add objects of type someclass as shown in the below code
snipet.
Abstract class is a half defined parent class. The full implementation of abstract class is defined by the
child classes.
For example below code snippet shows a simple abstract class / half defined class called
“DatabaseCommon” and later the concrete classes i.e. “SQLServer” and “Oracle” inherit and define a
complete implementation for the same.
To define an abstract class we need to use the abstract keyword.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
public abstract class DatabaseCommon
{
}
public class SQLServer : DatabaseCommon
{
}
public class Oracle : DatabaseCommon
{
}
Abstract classes can have abstract methods. Abstract methods when defined in a parent class
have to be implemented in the child classes. If abstract methods are not implemented it will
throw a error.
What is an Interface?
Interface is a contract that defines the signature of the functionality. It looks like a class but has no
implementation. It has only empty definition of methods, functions, events, and indexer.
Interfaces provide forced implementation. For instance in the below code snippet we have created a
simple interface called as “IDbCompulsory”. The below classes who implement interface
“IDbCompulsory” has to provide implementation for “ExecSql”.
interface IDbCompulsory
{
void ExecSql();
}
public class SQLServer : IDbCompulsory
{
public void ExecSql()
{
// Here code for firing SQL Server SQL statements
// are written
}
}
public class Oracle : IDbCompulsory
{
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
public void ExecSql()
{
// Here code for firing Oracle SQL statements
// are written
}
}
No.
If you define all methods,function, properties as abstract in abstract class it inhibits the same behavior as
an interface.
If we want to update interface with new methods, what is the best practice?
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
The biggest use of interface is to ensure that strict CONTRACT is followed between clients and
components. So that when changes happen on the components clients do not have to change too
much. In real world CONTRACTS between two parties do not change which implies that
interfaces should also not change.
So if you want to add new methods or change methods in interfaces the best practice is to create
new interfaces by inheriting. With this approach your older client who are using the interface
stay happy and the new clients who want those new or changed methods get the benefits of the
new functionality.
Let’s consider you have a simple interface called as “IView” which helps you to view data ,
below is the code for the same. Let’s consider that this interface is consumed by many clients.
interface Iview
{
public void View();
}
Over a period of time some users demand “Edit” functionality as well but the rest of the users are
happy with the ‘View” functionality and they do not want them to get affected by these changes.
Now if you go and change this interface ( “IView”) a.k.a you will be disturbing everyone.
So the best option would be to add a new interface i.e. “IEdit” which inherits from “IView”. So
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
the “IEdit” will have the functionality for “Edit” as well as “View” because it’s also inheriting
from “IView”. And the clients who are consuming “IView” do not need to update as “IView’ is
not changed at all.
So putting this whole story in one single sentence for the interviewer.
Interface once fixed should not be changed. If we ever have to add new
functions, new interfaces should be created so that we do not break
compatibility with old clients.
What is a delegate?
Delegate is an abstractpointer to a function or method. In other words you can create a pointer which
points to a method or function and then pass that pointer wherever you wish and invoke the function /
method.
• Declare a delegate.
• Create an object reference.
• Point the reference to the method.
• Invoke the method via the delegate.
// Declare a delegate
public delegate int PointToAdd(int i, int y);
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Normally when you create a delegate, your delegate points to only one function or method. In case you
want to point multiple functions and invoke them sequentially, you need to use the multicast delegate.
To point to multiple function using delegate pointer we need to use “+=” sign as shown in the below code
snippet.
ptrcall += Method1;
ptrcall += Method2;
Events are higher level of encapsulation over delegates. Events use delegates internally.
Delegates are naked and when passed to any other code, the client code can invoke the delegate.
Event provides a publisher / subscriber mechanism model.
So subscribers subscribe to the event and publisher then push messages to all the subscribers.
Below is a simple code snippet for the same :-
MyEvent();
obj.MyEvent += Function1;
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
What is the difference between delegate and events?
They can not be compared because one derives from the other.
• Actually, events use delegates in bottom. But they add an extra layer of security on the delegates,
thus forming the publisher and subscriber model.
• As delegates are function to pointers, they can move across any clients. So any of the clients can add
or remove events, which can be confusing. But events give the extra protection / encapsulation by
adding the layer and making it a publisher and subscriber model.
Just imagine one of your clients doing this
c.XyzCallback = null
This will reset all your delegates to nothing and you have to keep searching where the error is.
Yes.
Yes, you can have shared events, do note only shared methods can raise shared events.
What is shadowing?
Shadowing replaces the complete element of the parent class. For instance you can see in the below
sample code where the clsParent has a variable int “i” , which is replaced by the child class clsChild by a
method “i”.
In other words when you refer the parent object “i” it is a variable and when you refer the child object“i”
it is a method.
class clsParent
{
public int i=0;
}
class clsChild : clsParent
{
public new void i()
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
{
Console.WriteLine("Hey i became a method");
}
}
Overriding redefines only the implementation while shadowing redefines the whole element.
We can stop the class from further inheriting by using the "Sealed" keyword. For instance below
is a simple sample code where we have a class called as "Human" which is further inherited to
create a "Male" or "Female" class.
Now the below code is great but we do not anyone to further inherit from "Male" or "Female"
class. In simple words"Male" and "Female" are the last legs in this inheritance hierarchy. This
can be done by using the "Sealed" keyword.
If anyone tries to inherit the sealed classes he will end with the below error "cannot derive from sealed
type".
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
If you want to create an abstract class in VB.NET it’s done by using “Must Inherit” keyword. You cannot
create an object of a class, which is marked as “Must Inherit”. When you define “Must Inherit” keyword
for class, you can only use the class by inheriting.
Point 2:- If you want to have low memory foot print. For instance let’s say you want to plot a
graph. To plot a graph you need to have 100’s of objects created so that you can represent co-
ordinates. Now if you create a class and generate those 100’s of objects you end up putting lot of
load on your garbage collector. If you create a “struct” , it’s a value type. So they get created and
destroyed immediately. Thus putting less load on memory.
For all other scenarios use a class.
http://www.questpond.com
For more ma
aterials on
o .NET, mail
m us questpond
q d@questp
pond.com
m
Call on +91-22-667552917 / +91-99675907077
What does
d virtua
al keyworrd mean?
They signnify that meth
hod and propeerty can be ovverridden by thhe child classses.
What is
s ENUM and what are
a the benefits of using
u it?
if (leve
el == 0){C
Console.Wri
iteLine("B
Below quali
ity");}
else if (level ==
= 1){Consol
le.WriteLi
ine("Modera
ate qualit
ty");}
else if(
(level == 2){Console
e.WriteLin
ne("High qu
uality");}
Now by declaring
d a sim
mple enum caalled as Qualitty as shown below.
b
enum Qua
ality
{
Lo
ow = 0,
Mo
oderate = 1,
Hi
igh = 2
};
h
http://www
w.questpo
ond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Our code would look more readable as shown below. The other big benefit is if we change the numeric
values of quality we do not have to change throughout the project. So we can go a change the Low quality
to 1 and no change in code is required.
“Flags” is an ENUM attribute. If you want to set multiple values to an ENUM we need to use Flags.
[Flags]
enum MyColors
{
Green = 0,
Red = 1,
Blue = 2
};
In the below code we are setting “MyColors” ENUM to “Blue” and “Green” value.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
We can use “GetValues()” method of the “ENUM” class which returns an array of enum values.
var x = Enum.GetValues(typeof(MyColors));
“ENUM.Parse” parses string to an ENUM value. Like in the below code we pass “Green” string value
and it gets type casted to enum which has green enum as a constant.
If you create the child class object which constructor will fire first?
public class class1
{
public class1(){}
}
When we create a private constructor, we cannot create object of the class. Private constructors are used
when we want only a single instance of the class to be created and externally no one can use the ‘new’
keyword to create the object.
Yes, we can have different access modifiers. The below code will compile perfectly well.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
{
get
{
return _Custname;
}
protected set
{
Custname = value;
}
}
How can you define a property read only for external world and writable in the
same assembly?
Let’s us first try to understand this question. Let’s say if you have a class called as “Customer” with a
property “CustomerCode”.Now you want that anyone can read from the “CustomerCode” property but
this property can only be set from within the assembly.
In other words any one can run the below code.
But setting of the value can be only done from within assembly. The below code will run only if
it’s within assembly and it will throw error if it’s external to the assembly.
This can be achieved by have different access modifiers for “SET” and “GET properties on the
“CustomerCode” property.
So for the “GET” we will have public access modifiers and for “SET” we will apply internal
access modifiers. Now because “GET” is public this property can be read anywhere and because
the “SET” is internal it can only be accessed from within assembly. Below goes the code for the
same.
class Customer
{
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
private string _CustomerCode = "";
public string CustomerCode
{
get { return _CustomerCode; }
internal set { _CustomerCode = value; }
}
}
Yes, the finally code will run even though there is a return statement in the try. Finally block will run
irrespective what happens in try block. That’s the reason why finally block is a good place to put clean up
code.
What is an Indexer?
Many time classes have contained (aggregated or composed) collections. For example in the
below code you can see we have a customer class which has an address collection.
publicclassCustomer
{
privateList<Address> Addresses = newList<Address>();
}
Now let’s say we would like to like fetch the addresses collection by “Pincode” and
“PhoneNumber”. So the logical step would be that you would go and create two overloaded
functions one which fetches by using “PhoneNumber” and the other by “PinCode”. You can see
in the below code we have two functions defined.
publicAddress getAddress(int PinCode)
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
{
foreach (Address o in Addresses)
{
if (o.Pincode == PinCode)
{
return o;
}
}
returnnull;
}
publicAddress getAddress(string PhoneNumber)
{
foreach (Address o in Addresses)
{
if (o.MobileNumber == PhoneNumber)
{
return o;
}
}
returnnull;
}
Now on the client side your code would look something as shown below.
Customer Customers = newCustomer();
Customers.getAddress(1001);
Customers.getAddress("9090");
Now the above code is great but how about simplifying things further. How about something
more simple as shown in the below code. In other words we want to INDEXED the class itself.
Customer Customers = newCustomer();
Address o = Customers[10001];
o = Customers["4320948"];
You can see the below image where we can have two overloaded indexers “PinCode” and
“PhoneNumber”.
This can be achieved by using an indexer. There are two things we need to remember about
indexer:‐
• “Indexer” is defined by using “this” keyword.
• “Indexer” is a property so we need to define set and get for the same.
Below is the code implementation for indexer. You can see we have used “this” keyword with
two overloaded function one which will fetch us address by using the “phonenumber” and the
other by using “pincode”.
publicclassCustomer
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
{
privateList<Address> Addresses = newList<Address>();
publicAddressthis[int PinCode]
{
get
{
foreach (Address o in Addresses)
{
if (o.Pincode == PinCode)
{
return o;
}
}
returnnull;
}
}
publicAddressthis[string PhoneNumber]
{
get
{
foreach (Address o in Addresses)
{
if (o.MobileNumber == PhoneNumber)
{
return o;
}
}
returnnull;
}
}
}
Once you put the above “indexer” code you should be able to access the address collection from
the customer object using an indexer “[]” as shown in the below figure.
Summarizing in one sentence: - Indexers helps to access contained collection with in a class
using a simplified interface. It’s a syntactic sugar.
No.
Chapter 4: ADO.NET
What are the different components in ADO.NET?
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
• Connection: -This object creates a connection to the database. If you want to do any operation on the
database you have to first create a connection object.
• Command: -This object helps us to execute SQL queries against database. Using command object we
can execute select, insert, update and delete SQL command.
• Data reader: - This provides a recordset which can be browsed only in forward direction.It can only
be read but not updated. Data reader is good for large number of records where you want to just
browse quickly and display it.
• Dataset object: -This provides a recordset which can be read back and in forward direction. The
recordset can also be updated. Dataset is like a in memory database with tables, rows and fields.
• Data Adapter: -This object acts as a bridge between database and dataset; it helps to load the dataset
object.
• Data View: - This object is used to sort and filter data in Data table of dataset.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
What is the namespace in which .NET has the data functionality class?
This namespace has the dataset object which helps us to access data in a data source independent manner.
System.Data.SqlClient:
This namespace has objects which helps us to connect to SQL Server database.
System.Data.OleDB
This namespace has objects which helps us to connect to other databases like Oracle, Access and also
SQL Server database.
System.XML
This Contains the basic objects required to create, read, store, write, and manipulate XML documents.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
If you want to connect only to SQL Server use sqlclient or else use oledb. Oledb also connects to other
database plus sql server .Sqlclient is meant specifically meant for SQL server so has better performance
as compared to oledb.
Following are some major differences between dataset and data reader:-
• Dataset is a disconnected architecture while data reader is connected architecture.
• Data Reader provides forward-only and read-only access to data, while dataset moves back as
well as forward.
• Datasetobject isan in-memory database with tables , rows and columns while datareader is
just simple table which can be read only in a forward direction.
• Dataset can persist contents while data reader cannot persist contents, they are read only
and forward only.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
What is the use of command objects?
Command object helps to execute SQL statements. Following are the methods provided by command
object:-
• ExecuteNonQuery: -Executes insert, update and delete SQL commands. Returns an Integer
indicating the number of rows affected by the query.
• ExecuteReader: - Executes select SQL statements which can either be in your .NET code or
in a stored procedure. Returns a "Datareader" object.
• ExecuteScalar: - Executes SQL command and returns only a single value like count,sum ,
first record etc.
Dataset is an in memory object with data tables, rows and columns. You can visualize it as in-memory
RDBMS.Dataset has the following features:-
• The in memory RDBMS works in a disconnected manner. In other words even if the connection is
closed the dataset is still there in memory.
• You can do modification in the in-memory database object and send the final changes to the
database.
Below is a simple code snippet which shows how to access a column value. You can see how the full
dataset object hierarchy is accessed to get the column value.
objDataset.Tables[0].Rows[0]["CustCode"]
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
What is the use of data adapter?
Data adapter object acts like a bridge it helps to load the dataset object. Below is a simple code snippet
which shows how the dataadapter object is created and then using the fill method the dataset object is
loaded.
Update: -Updates the original datasource with the changes made to the content of the DataSet.
With objConnection
.Connection String = strConnectionString
.Open()
EndWith
• Create the command object with the SQL. Also, assign the created connection object to command
object and execute the reader.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Breeder = .Execute Reader ()
EndWith
• You can then loop through the reader object to read the data.
Do while objReader.Read ()
lstData.Items.Add (objReader.Item (“First Name”))
Loop
• Do not forget to close the connection object.
objConnection.close*();
ADO.NET provides the SqlCommand object, which provides the functionality of executing stored
procedures. In the command type we need to provide the command type as stored procedure as shown in
the below code snippet.
How can we force the connection object to close after my data reader is
closed?
Command method Execute reader takes a parameter called as Command Behavior wherein we can
specify saying close connection automatically after the Data reader is close.
I want to force the data reader to return only schema of the data store
rather than data.
How can we fine-tune the command object when we are expecting a single
row?
Again, CommandBehaviour enumeration provides two values Single Result and Single Row. If you are
expecting a single value then pass “CommandBehaviour.SingleResult” and the query is optimized
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
accordingly, if you are expecting single row then pass “CommandBehaviour.SingleRow” and query is
optimized according to single row.
Config files are the best places to store connection strings. If it is a web-based application “Web.config”
file will be used and if it is a windows application “App.config” files will be used.
Create object ofdata adapterand call the fill command method of the adapter.
What are the various methods provided by the dataset object to generate
XML?
• ReadXML
Read’s a XML document in to Dataset.
• GetXML
This is a function, which returns the string containing XML document.
• Writexml
This writes a XML data to disk.
Dataset has “AcceptChanges” method, which commits all the changes since last time “Acceptchanges”
has been executed.
How can we check which rows have changed since dataset was loaded?
For tracking down changes, Dataset has two methods, which comes to rescue “Get Changes “and “Has
Changes”.
Get Changes
Returns dataset, which are changed since it, was loaded, or since Accept changes was executed.
Has Changes
Or abandon all changes since the dataset was loaded use “Reject Changes This property indicates that has
any changes been made since the dataset was loaded or accept changes method was executed.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Note:- One of the most misunderstood things about these properties is that it
tracks the changes of actual database. That is a fundamental mistake;
actually the changes are related to only changes with in dataset and have
nothing to with changes happening in actual database. Dataset are
disconnected and do not know anything about the changes happening in actual
database.
“Data table” provides “NewRow” method to add new row to “Data Table”. “Data Table” has
“DataRowCollection” object that has all rows in a “Data Table” object. Following are the methods
provided by “DataRowCollection” object:-
Add
Adds a new row in Data Table
Remove
It removes a “Data Row” object from “Data Table”
Remove At
It removes a “Data Row” object from “Data Table” depending on index position of the “Data Table”.
“DataView” is used for sorting and finding data within “data table”.
Data view has the following methods:-
Find
It takes an array of values and returns the index of the row.
Find Row
This also takes array of values but returns a collection of “Data Row”.
If we want to manipulate data of “Data Table” object create “Data View” (Using the “Default View” we
can create “Data View” object) of the “Data Table” object and use the following functionalities:-
Add New
Adds a new row to the “Data View” object.
Delete
Deletes the specified row from “Data View” object.
objCommand.CommandText = "Table1"
objDataAdapter.Fill(objDataSet, "Table1")
objCommand.CommandText = "Table2"
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
objDataAdapter.Fill(objDataSet, "Table2")
Above is a sample code, which shows how to load multiple “Data Table” objects in one “Dataset” object.
Sample code shows two tables “Table1” and “Table2” in object ObjDataSet.
lstdata.DataSource = objDataSet.Tables("Table1").DefaultView
In order to refer “Table1” Data Table, use Tables collection of Datasets and the Default view object will
give you the necessary output.
Command Builder builds “Parameter” objects automatically. Below is a simple code, which uses
command builder to load its parameter objects.
Concurrency issues happen in multiuser environment when multiple people update the same data
at the same time.
• User A fetches data with value “X” and starts changing this value to “Y”.
• User B also fetches the same “X” data and starts changing this value to “Z”.
• Now User B first updates the data to database. In other words he changes the data to “Z”.
• Now User A also sends the update to database. In other words he changes the data to
“Y”.
Now User A thinks he has changed “X” to “Y” and User B thinks the current data is “Z”. Both of
them are wrong and this leads to confusion termed as “Concurrency” problem.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
In optimistic locking there is no locking actually. It only checks if the old values are changed, in case
they are changed it means somebody has changed the data, so it raises exception.
In pessimistic locking you actually lock the record, depending on the type of lock no other process can
make modifications to the record.
Pessimistic locking is done by using transaction isolation levels like read committed, read uncommitted,
repeatable read and serializable.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
How can we perform transactions in .NET?
The most common sequence of steps that would be performed while developing a transactional
application is as follows:
• Open a database connection using the Open method of the connection object.
• Begin a transaction using the Begin Transaction method of the connection object. This
method provides us with a transaction object that we will uselater to commit or rollback the
transaction. Note that changes caused by any queries executed before calling the Begin
Transaction method will be committed to the database immediately after they execute. Set
the Transaction property of the command object to the above mentioned transaction object.
• Execute the SQL commands using the command object. We may use oneormorecommand
objects for this purpose, as long as the Transaction property of all the objects is set to a valid
transaction object.
• Commit or roll back the transaction using the Commit or Rollback method of the transaction
object.
• Close the database connection.
Can you explain the difference between an ADO.NET Dataset and an ADO
Record set?
There two main basic differences between record set and dataset:-
• With dataset you can retrieve data from two databases like oracle and sql server and merge them in
one dataset , with record set this is not possible
• All representation of Dataset is using XML while record set uses COM.
• Record set cannot be transmitted on HTTP while Dataset can be.
When a connection is opened first time, a connection pool is created and is based on the exact match of
the connection string given to create the connection object. Connection pooling only works if the
connection string is the same. If the connection string is different, then a new connection will be opened,
and connection pooling will not be used.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
Let us try to explain the same pictorially. In the above figure, you can see there are three requests
“Request1”, “Request2”, and “Request3”. “Request1” and “Request3” have same connection string so no
new connection object is created for “Request3” as the connection string is same. They share the same
object “ConObject1”. However, new object “ConObject2” is created for “Request2” as the connection
string is different.
Note: - The difference between the connection string is that one has “User
id=sa” and other has “User id=Testing”.
Maximum pool size decides the maximum number of connection objects to be pooled. Ifthe maximum
pool size is reached and there is no usable connection available the requestis queued until connections are
released back in to pool. So it’s always a good habit tocall the close or dispose method of the connection
as soon as you have finishedwork with the connection object.
http://www.questpond.com
For more materials on .NET, mail us [email protected]
Call on +91-22-66752917 / +91-9967590707
For .NET it is enabled by default but if you want to just make yourself double sure , set Pooling=true
inthe connection string. To disable connection pooling set Pooling=false in connectionstring if it is an
ADO.NET Connection.
If it is an OLEDBConnection object set OLEDB Services=-4 in the connection string.
http://www.questpond.com