Você está na página 1de 30

1.What is the Postback in ASP.NET?

A postback is a request sent from a client to server from the same page, user is already working with.

o Add a new ASP.NET web form page to a project e.g. WebForm1.aspx.


o View the page code in HTML Source view.

Look the form line of code.

<form id=form1 runat=server>;


It represents a server-side implementation of form control.

Now just run the application to see WebForm1.aspx page and view its source code. HTML source
of the page will display form element as follows:
<code>form id="form1" action="WebForm1.aspx" method="post"&gt;
You can see that an HTML form element generated with an HTTP method as POST and
action=WebForm1.aspx. So, if a submit button is clicked, the page will postback to itself by
default.
Following figure will also give you more understanding on ASP.NET Postback.

You can read more on postback vs Callback difference here.

2. Difference between ASP.NET WebForms and ASP.NET MVC?


ASP.NET Web Forms uses Page controller pattern approach for rendering layout. In this approach, every
page has its own controller i.e. code-behind file that processes the request. On the other hand, ASP.NET
MVC uses Front Controller approach. In this approach a common controller for all pages, processes the
requests.

ASP.net web form ASP.net MVC

Page controller pattern that means an implicit Front controller pattern that means
controller (code behind) would process the request anexplicitcontroller would be there to process the
request

web form has user controls for code reusability Partial views has code reusability

view and controllers are not separated view and controller are handled separately

stateful and view state is used to maintain state Stateless, so view state is not used
Has server control Has html helper

views are tightly coupled with business logic views and logics are separately managed

Master pages for constant look and feel MVC layouts for constant look and feel

Filebased urls and it needs physical files Route based urls and doesnot need a physical file.
It depends on controller

Recommended for small scale applications Recommended for large scale applications

3.Please briefly explain ASP.NET Page life Cycle?


Initialization: Controls raise their Init event in this stage.Objects and variables are initializes for complete
lifecycle of request.
LoadViewState: is a post back stage and loads the view state for the controls that enabled its view state
property.

LoadPostBackData: is also a post back stage and loads the data posted for the controls and update
them.
Load: In this stage page as well as all the controls raise their Load event. Till this stage all the controls
are initialized and loaded. In most of the cases, we are coding this event handler.
RaisePostBackEvent: is again a postback stage. For example, its raise against a button click event. We
can easily put our code here to perform certain actions.
SaveViewState: Finally, controls state is saved in this stage before Rendering HTML.
Render: This is the stage where HTML is generated for the page.
Dispose: Lastly, all objects associated with the request are cleaned up.

You can see the detailed explanation on ASP.net page life cycle here

4.What is the difference between custom controls and user controls?


Custom controls are basically compiled code i.e. DLLs. These can be easily added to toolbox, so it can
be easily used across multiple projects using drag and drop approach. These controls are comparatively
hard to create.
But User Controls (.ascx) are just like pages (.aspx). These are comparatively easy to create but tightly
couple with respect to User Interface and code. In order to use across multiple projects, we need to copy
and paste to the other project as well.

5.Please briefly explain the usage of Global.asax?


Global.asax is basically ASP.NET Application file. Its a place to write code for Application-level events
such as Application start, Application end, Session start and end, Application error etc. raised by
ASP.NET or by HTTP Modules.

There is a good list of events that are fired but following are few of the important events in Global.asax:

Application_Init occurs in case of application initialization for the very first time.
Application_Start fires on application start.
Session_Start fires when a new user session starts
Application_Error occurs in case of an unhandled exception generated from application.
Session_End fires when user session ends.
Application_End fires when application ends or time out.

You can read the detailed article here.

6.What is the concept of view state in ASP.NET?


ViewState of a webform is available only within that webform
ViewState is stored on the page in a hidden field called viewState. it will be lost if the user will
navigate away from the page or if browser is closed
ViewState is used y all asp.net controls to retain their state across postback

You can read the difference between view state,session state and Application state here.
7.Difference between Response.Redirect and Server.Transfer?
Both Server.Transfer and Response.Redirect are ASP.NET objects and are used for navigation between
web-pages. However, there are noticeable differences between these two techniques:
Response.Redirect()

Response.Redirect() redirects the user to another web-page which may or may not be on
thesame server. It can redirect the user to an external website on a different server.
Response.Redirect() updates the address bar and adds the updated URL to the browser history.
User can click back on the browser to navigate to the previous page.
Response.Redirect() terminates the request with HTTP 302 status and client-side roundtrip.
Client then navigates to the new address and the browser address bar and history updates. The
client pays the cost of additional round-trips to the server on each request.
Form variables are are not transferred upon a call to Response.Redirect().

Server.Transfer()

Server.Transfer() quits current execution of the web-page and redirects the user to another web-
page on thesame server. It cannot send the user to an external website on a different server.
Server.Transfer() keeps the URL unchanged in the address bar. It happens entirely on the
server side and the client browsers address bar remains constant. User cannot click on back
button on the browser to navigate to the previous page
Server.Transfer() reduces the server request and conserves server resources. It simply changes
the focus on the Web Server and transfers the request. With Server.Transfer() there are less
number of HTTP requests, which eases pressure on the Web Server and makes the application
execute faster.
Developer can transfer Query Strings and form variables with a little bug-bashing. The
Server.Transfer()method has a second parameter preserveForm. If this is set to True, the
existing query string and form variables will be available to the transferred page. Ex
Server.Transfer(webpage2, True);

8.What are the different types of Validation controls in ASP.NET?


In order to validate user input, ASP.NET provides validation server controls. All validation controls inherits
from BaseValidator class which contains the common validation properties and methods like
ControlToValidate, Enabled, IsValid, EnableClientScript, ValidationGroup,Validate() etc.

ASP.Net provides a range of validation controls:

RequiredFieldValidator validates required input.


RangeValidator validates the range. Validates that input is between the given range values.
CompareValidator validates or compares the input of a control with another control value or with
a fixed value.
RegularExpressionValidator validates input value against a defined regular expression pattern.
CustomValidator allows to customize the validation logic with respect to our application logic.
ValidationSummary displays all errors on page collectively.

9.What are HttpHandlers and HttpModules in ASP.NET?


HttpHandler: ASP.NET Engine uses HttpHandlers to handle specific requests on the basis of its
extensions. ASP.NET Page Handler handles all requests coming for (.aspx) pages. We can define our
own custom HttpHandler to handle a specific request with a specific extension, say .jpeg, .gif, or .ahmad.
But there will always be only one handler for a specific request.

HttpModule: ASP.NET Engine uses HttpModules to inject some specific functionality along with
ASP.NET default functionality for all incoming requests regardless of its extensions. There are a number
of built-in modules already available in ASP.NET HTTP Pipeline. But we can write our own custom HTTP
module to perform some additional functionality (for example, URL rewriting or implementing some
security mechanism) for all incoming requests.
We have discussed HttpHandler and HttpModule in detailed here.

10.What are the types of Authentication in ASP.NET?


There are three types of authentication available in ASP.NET:

Windows Authentication: This authentication method uses built-in windows security features to
authenticate user.
Forms Authentication: authenticate against a customized list of users or users in a database.
Passport Authentication: validates against Microsoft Passport service which is basically a
centralized authentication service.

11.What are Session state modes in ASP.NET?


ASP.NET supports different session state storage options:

In-Process is the default approach. It stores session state locally on same web server memory
where the application is running.
StateServer mode stores session state in a process other than the one where application is
running. Naturally, it has added advantages that session state is accessible from multiple web
servers in a Web Farm and also session state will remain preserved even web application is
restarted.
SQLServer mode stores session state in SQL Server database. It has the same advantages as
that of StateServer.
Custom modes allows to define our custom storage provider.
Off mode disables session storage.
12.Hyperlink Vs LinkButton in ASP.NET?
A Hyperlink redirects to a given URL identified by NavigateURL property but a LinkButton which actually
displays a Hyperlink style button causes a postback to the same page but it doesnt redirect to a given
URL.

13.Globalization Vs Localization
When we need to build an application that work for multiple cultures e.g en-US, ar-SAetc, this process of
designing and building applications that work for more than one cultures is called globalization. However,
customizing an application for a specific culture is localization. Both globalization and localization
normally go together.

14. How to access information about a users locale in


ASP.NET?
Users locale information can be accessed through System.Web.UI.Page.Culture property.

15.Cache Management in ASP.NET?


ASP.NET provided support for Cache Management in almost all versions. In .NET Framework 3.5 and
older, the support for caching was provided through classes available in System.Web.Caching. But this
support was limited to System.Web meaning for ASP.NET Web Applications only. Now, with .NET
Framework 4.0 and later, this support is enhance to non-Web Applications also by providing APIs
in System.Runtime.Caching.

ASP.NET supports three types of Caching:


o Page Output Caching
o Partial Page Caching
o Data Caching

16.Difference between Culture and UICulture properties in


ASP.NET?
CultureInfo class plays an important role for localizing our application pages. Culture is specific in
localizing non-visual parts of the page like DateTime, Currency, number formatting etc.

while UICulture is specific in localizing visual part of a webpage like Language being used to display the
contents of the web page.

17.What is State Management?

HTTP is a stateless protocol by nature. So, we need some mechanism to preserve state (i.e. state of a
webpage, a control or an object etc.) between subsequent requests to server from one or more clients.
and this mechanism is referred as State Management in ASP.net

You can read more detailed article on state management here.

18.What are the State Management Techniques used in


ASP.NET?
State Management techniques used in ASP.NET can be categorized in two types:

1. Client-Side State Management


o View State
o Control State
o Hidden Fields
o Cookies
o Query String
2. Server-Side State Management
o Application State
o Session State
o Profile Properties
o Cache

You can read more detailed article on state management here.

19.What is ViewState? or Explain ViewState as State


Management Technique?
ViewState is one of the Client-Side State Management techniques that provides page-level
state management, which means state is preserved between subsequent requests to same page.
By using this technique, state of the page along with its controls is stored in a hidden form field
i.e. __VIEWSTATE and this field is again available on server when page is posted back with
HTTP Request.
ViewState data is encoded in Base64 String encoded format.
ViewState can be enabled or disable at different levels:
o Control Level
ViewState for a specific control can be enabled or disabled by
setting EnableViewState
o Page Level
ViewState for a specific control can be enabled or disabled by
setting EnableViewState
o Application Level
For whole application, we can enable/disable views in configuration file.

20.What is the difference between Application and Session


State?
Application state is basically a common data repository for an applications all users and their all
sessions. On the other hand, Session state is specific to a single user session. You can read more
detailed explanation here.

21.What is the difference between Session.Clear() and


Session.Abandon() in ASP.NET?
Session is a Collection and it stores data as Key/Value pair.

Session.Clear() clears all the session values but doesnt destroy the Session.

Session.Abandon() destroys the session object.

In otherwords ,Session.Clear() is like deleting all files inside a folder (say Root) but Session.Abandon()
means deleting the Root folder.

22.Difference between Local and Global resources?


Resources for a localized ASP.NET application can be stored locally as well as globally.

Local resources are specific to web page and stored in a folder App_LocalResources.

It can be accessible to that specific page only. Global resources are accessed by almost all application
pages and stored in App_GlobalResources folder.

23.What is the difference between Label Control and Literal Control?


A Label control in ASP.NET renders text inside <span> tags while a Literal Control renders just the text
without any tags.
With Label controls we can easily apply styles using its CssClass property, however, if we dont want to
apply style/formatting, its better to go for a Literal control.

24.What is the difference between var and dynamic?


var dynamic
Introduced in C# 3.0 Introduced in C# 4.0

Statically typed This means the type of variable declared is decided Dynamically typed This means
by the compiler at compile time. the type of variable declared is
decided by the compiler at run
time.

var type of variables are required to be initialized at the time of No need to initialize at the time of
declaration or else they encounter the compile time error: Implicitly- declaration.
typed local variables must be initialized.

e.g., var str=I am a string; e.g., dynamic str;

Looking at the value assigned to the variable str, the compiler will treat str=I am a string; //Works fine
the variable str as string. and compiles

Errors are caught at compile time. Errors are caught at runtime

Since the compiler knows about the type and themethods and Since the compiler comes to
properties of the type at the compile time itself about the type and the methods
and properties of the type at the
run time.

Intellisense help is available for the var type of variables. This is Intellisense help is not available
because, its type is inferred by the compiler from the type of value it is for dynamic type of variables
assigned and as a result, the compiler has all the information related to since their type is unknown until
the type run time. So intellisense help is
not available. Even if you are
informed by the compiler as This
operation will be resolved at run-
time.

will throw a compile error since the variable is not initialized. The Will compile
compiler needs that this variable should be initialized so that it
can infera type from the value.

25. Difference between String and StringBuilder?


String StringBuilder

A string (namespace: System.String ) is a A StringBuilder (System.Text.StringBuilder) represents a


sequential collection of Unicode characters that mutable string of characters. This class cannot be
represents text inherited.

String is immutable, Immutable means if you StringBuilder is mutable, means if create string builder
create string object then you cannot modify it object then you can perform any operation like insert,
and It always create new object of stringtype in replace or append without creating new instance
memory. forevery time.it will update string at one place in memory
doesnt create new space in memory.

Any operation that appears to change the string, Any operation that appears to modify or append new
it creates a new instance of stringtype in string, it doesnt create a new instance of string typein
memory memory

The maximum size of a String object in memory The default capacity of this object is 16 characters, and
is 2 GB (about 1 billion characters). its maximum capacity is more than 2 billion characters.

Example:string strMyValue = Hello Visitor; Example:StringBuilder sbMyValue = new


// create a new string instance instead of StringBuilder();
changing the old one sbMyValue.Append(Hello Visitor);
strMyValue += How Are; sbMyValue.Append(How Are You ??);
strMyValue += You ??; string strMyValue = sbMyValue.ToString();

String is slower as compare to string builder StringBuilder is faster as compare to string object when
object when we deals with large size of strings we deals with large size of strings

String is efficient when we deals with static or StringBuilder is efficient when we deals with dynamic or
smaller size of string means we dont need to larger size of string means we want to modify that string
modify later on later on

Although a string is a reference type, the


equality operators (== and !=) are defined to
compare thevalues of string objects, not
references. However after boxing the
comparison happens on string instances.
1. What is Caching and what are the pros and cons of using it?
Caching is a mechanism that improve performance for an application by storing data in memory for fast
access.
When the application will access data from Cache (i.e. in-memory) instead of fetching it from original data
store (may be a database), it will definitely improve performance.
But Caching benefits are not limited to performance only, it also improve application Scalability as well as
Availability.

Load on server is reduced when data is fetched from Cache instead of original source, thus
improving scalability of an application.
Caching normally keep serving application data even if the original source is temporarily down,
thus improving availability of an application.

Advantages:

The advantages of web caching via proxy servers include:

faster access to valid cached resources


saving on costly use of bandwidth
imposing controls on access to dubious material
collecting useful statistics on web access
providing cached resources even when origin server is down

Disadvantages:

Disadvantages of web caching include

slower performance if the resource isnt found in the cache


being given a stale copy of a resource when an uptodate copy is needed
resources sometimes getting mangled/lost on route
sharing an access point to the web increasing risks to service
proxy server access logs invading the privacy of users
proxy intermediary confusing logging and access control by subscription services

2. Cache Management in ASP.NET?


ASP.NET provided support for Cache Management in almost all versions. In .NET Framework 3.5 and
older, the support for caching was provided through classes available in System.Web.Caching. But this
support was limited to System.Web meaning for ASP.NET Web Applications only. Now, with .NET
Framework 4.0 and later, this support is enhance to non-Web Applications also by providing APIs in
System.Runtime.Caching.
ASP.NET supports three types of Caching:

Page Output Caching


Partial Page Caching
Data Caching

3. Page Output Cache Vs Partial Page Cache Vs Application Data


Cache in ASP.NET?
Page Output Cache
In case of Page Output Cache, the output of a complete web page is stored in a cache.
So, when that web page is accessed again, it will be loaded from cache instead of fetching page data
again from data source.

Partial Page Cache


For Partial Page Cache (also known as Page Fragment Cache), a part or fragment of a web page is
stored in Cache as opposed to complete page caching for Page Output Cache.
For example, caching a user control on a web page that displays product categories using Page
Fragment Cache.

Data Cache
In some scenarios, we may store frequently used objects into cache using ASP.NET Cache API.
So, later on, that object will be loaded from cache instead of instantiating object again and fetching data
from original source for it.

4. Authentication Vs Authorization?
Authentication and Authorization are two key security related concepts that are independent but normally
go together.

Authentication is a process that verifies the identity of a user. On ther hand, Authorization is the process
of assigning rights/privileges to already authenticated user.

For example, when a user tries to login a web application. First of all, user identity is verified that either
he/she is valid registered user of application.
If his/her identity validated successfully then appropriate privileges are assigned accordingly.
Different users may have different privileges on same application, for example, user1 can only view/read
some records while user2 may have privileges for all CRUD (Create, Read, Update, Delete) operations
on same data.

5. What is Protected Configuration in ASP.NET?


While developing an ASP.NET application, we normally store a number of important sensitive information
in our config files like encryption keys, connection strings etc. Application vulnerability increases if this
sensitive information is stored as plane text.
So Protected Configuration is an ASP.NET feature that enables to encrypt such sensitive information in
configuration files.
6. How to use Page Output Cache in ASP.NET?
Implementing Page Output Cache in ASP.NET is simple. For Page Output Caching, @
OutputCache directive is used on an ASP.NET page as follows:

<%@ OutputCache Duration=50 VaryByParam=None %>

Duration value is in seconds and it tells the page that how long to cache the contents?
Now, when we will access the page, it will verify that either it exists in Cache? if Yes, then verify that is it
expired? If not then fetch it from Cache and render otherwise create a new instance of the page and put it
back to Cache.

The other parameter of this directive is VaryByParam. If its value is specified to something as follows:

<%@ OutputCache Duration=50 VaryByParam=ProductId %>

Now, Cache is dependent on the value of this parameter, If the value of parameter remains same, page
will be fetched from Cache otherwise it will be refreshed again.For in-depth details on Page Output
Cache, follow here.

7. How to use Page Fragment or Partial Page Cache in ASP.NET?


Page Fragment Caching uses the same @ OutputCache directive with VaryByControl parameter as
follows:
<%@ OutputCache Duration=50 VaryByParam=None VaryByControl=ControlName %>

In this case, Cache is dependent on the value of Control specified in VaryByControl parameter. For
example, content on a page are dependent on the selected values of a dropdownlist, so, VaryByControl
will have the dropdownlist control name as value.

8. How to use Data Cache in ASP.NET?


We have already explained the usage of Data Cache above in this series of ASP.NET Interview
Questions that in particular situations, we need to store objects into cache. Adding an object to Cache
and accessing it from Cache is simple.

We can use Add method to add an object to Cache as:

1 Cache.Add(key, value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback); if (Cache[ProductKey] == null)


2 Cache.Add(ProductKey,

3 objProduct,

4 null,

5
DateTime.Now.AddSeconds(60),
6
Cache.NoSlidingExpiration,
7
CacheItemPriority.High,
8
null);

To retrieve it back:

1 Product objProduct = (Product) Cache[ProductKey];

9. What are the available Authentication modes in ASP.NET?


There are three types of authentication available in ASP.NET:

Windows Authentication: This authentication method uses built-in windows security features to
authenticate user.
Forms Authentication: authenticate against a customized list of users or users in a database.
Passport Authentication: validates against Microsoft Passport service which is basically a
centralized authentication service.

10. What is the difference between Windows Authentication and


Forms Authentication in ASP.NET?
Windows Authentication is a way to authenticate a user against Windows accounts. Windows
authentication mode is suitable for corporate users in windows environment.
In case of Forms Authentication, a separate list of users is maintained for authentication. For example, we
can maintain the list in database and authenticate user against it.
We can set authentication mode in web.config as follows:
<authentication mode=Forms>
11. What is Passport Authentication?
Passport authentication is a centralized authentication service provided by Microsoft that offers a
single logon and core profile services for member sites.

Passport benefits users because they do not need to log on to new limited-access resources or sites

Passport Authentication actually validates against a centralized authentication service i.e. Microsoft
Passport Service. We dont need to implement our own custom authentication mechanism if
implementing .NET Passport Single Sign-In (SSI) service.

12. Can you briefly explain how Passport Authentication works?


As discussed above that Passport Authentication is a central service. It just authenticate (validate the
credentials), no authorization (grant or deny access to a site). So, implementing application will check for
the Passport Authentication Cookie. In case of unavailability of Passport Cookie, user is redirected to
passport Sign-In page. User provides the credentials on Sign-In page, if validated, Authentication Cookie
is stored on client machine and redirected to the requested page.

13. What are the advantages of using Passport Authentication?


Advantages of Passport Authentication are:

1. The sign-in, sign-out, and registration pages are centrally hosted rather than being specific to
each individual site.
2. All .NET Passport sign-in and core profile cookies are strongly encrypted.
3. The central .NET Passport servers return encrypted sign-in and profile information to your site.
4. Members do not need to retype their sign-in name and password when moving from site to site.
5. Participating Web sites never receive a members password. The authentication cookie is actually
a pair of encrypted time stamps asserting when the member signed in.
6. There is no real-time, server-to-server communication between participating Web sites and the
central .NET Passport servers.
7. All information exchange occurs through the clients browser using HTTP redirects, encrypted
information on the query string, and cookies.

14. What is Role-based Security?


Authorization is a process of granting privileges or permissions on resources to an authenticated user.
So,
Role Based Security is a technique we use to implement authorization on the basis of users roles within
an organization. Its more granular approach to grant or revoke permissions on resources through users
roles.

An example of granting or revoking permissions in configuration file using windows built-in groups as
follows:
<authorization >
<allow roles=MyDomain1Administrators / > < ! Allow Admin of this domain >
<deny users=* / > < ! Deny anyone else. >
</authorization >

15. What are the different Security Controls in ASP.NET?


ASP.NET provides several security controls which are actually Web Server controls. You can find those in
your Visual Studio Toolbox.

Login Control:
In almost every application we need to take user credentials on a typical login page. Login control
provides the same standard functionality and reduces the effort for building it from scratch.

LoginName:
After a user successfully logged in to an application, we normally display his/her username to top right or
some other place on the page. Now, this functionality is provided by LoginName control.

LoginView Control:
LoginView control displays different view for different users. Using AnonymousTemplate and
LoggedInTemplate, different information can be presented to different users.

LoginStatus Control:
LoginStatus control implies whether a user is authenticated or not. For an unathenticated user, it displays
a link to login page. On the other hand, for authenticated user, a logout link is displayed.

LoginRecovery Control:
Password recovery is another important functionality simplified through PasswordRecovery control. It
sends an email with login credentials to registered user email.

16. What is Code-Access Security (CAS)?


Code Access Security (CAS), in the Microsoft .NET framework, is Microsofts solution to prevent
untrusted codefrom performing privileged actions. When the CLR loads an assembly it will obtain
evidence for the assembly and use this to identify the code group that the assembly belongs to.

Its .NET CLRs security system that restrict the code to perform an unwanted task by applying security
policies. Using CAS (Code Access Security), we can restrict what our code can do? and also what code
can call our code?

17. What are the key functions of Code Access Security?


Key functions of Code Access Security are:

Defines permissions and permission sets that represent the right to access various system
resources.
Enables code to demand that its callers have specific permissions.
Enables code to demand that its callers possess a digital signature, thus allowing only callers
from a particular organization or site to call the protected code.
Enforces restrictions on code at run time by comparing the granted permissions of every caller on
the call stack to the permissions that callers must have.

18. What .NET Tool can be used to Enable/Disable CAS?


Code Access Security Tool (Caspol.exe) can be used to turn Code Access Security ON or OFF as
follows:

caspol -security on
caspol -security off

We can also list all code groups using following command.

caspol -listgroups

19. What is Impersonation in ASP.NET?


When using impersonation, ASP.NET applications can execute with the Windows identity (user account)
of the user making the request.

Impersonation is commonly used in applications that rely on Microsoft Internet Information Services (IIS)
to authenticate the user. ASP.NET impersonation is disabled by default.

For example, if a user user1 logged in and IIS is setup to run as Network Service. If user1 call a piece of
code on another computer (may be a web service call), the other computer will see the IIS user instead of
user1. But we can enable impersonation to allow user1 to access the web service using its windows
identity instead of Network Service.

20. How to configure Impersonation in ASP.NET?


By default, impersonation is disabled in ASP.NET. Impersonation can be Enabled/Disabled as follows:

<configuration>
<system.web>
<identity impersonate=true/> <! To disable set impersonate=false >
</system.web>
</configuration>

Impersonate a specific user account as:

1. What is an Assembly?
Assemblies are the basic building blocks required for any application to work in .net realm.
Assemblies provides collection of types and resources that work together to form a logical unit of
functionality.
Assembly is a set of one or more modules and classes compiled in MSIL and Metadata.

2. What all are the components of Assembly?


Assembly Manifest
MSIL source code
Type Metadata
Resources

3. What all are the different type of Assemblies?


Private Assembly
o It is used by Single Application
o Private Assemblies are kept in a local folder in which client application is installed
Public Assembly
o Public Assembly is shared by multiple application
o Shared Assembly resides in GAC

4. What is Assembly Manifest?


Assemblies has a special logical unit called Manifest. It contains:

Assembly name
Version number
Culture
Strong Name information
Type Reference Information
List of all files in Assembly
Information on referenced assemblies

5. What is GAC?
GAC is a central repository in a system in which assemblies are registered to shared between
application.
GACUtil.exe is used to view and change the content of GAC in system
GAC can contain multiple versions on .net assemblies
Thegautil.exe/I<assembly_name> is used to install assembly in GAC

6. What is Metadata?
Assembly metadata describes every data type and member defined in the code.
it stores name, version, culture, public key of an Assembly
Also it stores the description of types like name, visibility, base class, interfaces, implemented etc.
Metadata of an assembly is sharable among applications that execute on different platforms

7. What is Native Image Generator?


The Native Image Generator is a tool that creates a native image from an Assembly and stores that
image to native image cache on the Whenever an assembly runs, this native image is automatically used
to compile original assembly. This improves the performance of the application by loading and executing
an assembly faster.

8. What is Satellite Assembly?


Satellite assemblies are assemblies that is used to deploy culture and language for an application. A
separate product id is assigned to each language and a satellite assembly is installed in language specific
sub directory.

9. How do you add/remove assembly from GAC?


you can add assembly by using below syntax:

gacutil /i [assemblyName | assemblyPath]

you can remove assembly by using below syntax:

gacutil /u [assemblyName | assemblyPath]

10.What is the difference between EXE and DLL?


EXE:

Executable file, can run independently


It runs in a separate process
It cant be reused in application
it has a main function

DLL:

Dynamic link library is used as part of EXE or other DLLs


It runs in application process memory,
It can be reused in application
It does not have a main function

1. What is Object Oriented Programming?


OOP is a technique to develop logical modules, such as classes that contains properties, fields and
events. OOP provides many concepts such as inheritance, data binding, polymorphism etc.
Object means a real word entity such as pen,paper, chair, table etc.

Object-Oriented Programming is a methodology or paradigm to design a program using classes and


objects.

It simplifies the software development and maintenance by providing some concepts:

Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation

Simula is considered as the first object-oriented programming language.

2. What is a class?
A class can be defined as the primary building block of OOP. A class contains data and behavior of an
entity.

A class in C# can contain:

1. data member
2. properties
3. constructor
4. methods

Notes:
1. Class name should start with uppercase letter and be a noun e.g. String, Color, Button, System,
Thread etc.
2. The name of the constructor is always same as the class name
3. A class can have any number of data members, properties, constructors and methods
4. Data member defined using a class is called as object reference.
5. A class can have a data member which is an object reference of the same class Like the manager of
the employee is also a employee.

3. What is an Object?
An entity that has state and behavior is known as an object e.g. pen, table, car etc. It can be physical or
logical.

An object has three characteristics:

state: represents data (value) of an object.


behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible
to the external user. But,it is used internally by the compiler to identify each object uniquely.

For Example: Pen is an object. Its name is Parker, color is black etc. known as its state. It is used to write,
so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects are created. So object
is the instance(result) of a class. For example, you have a class called Vehicle and car is the object of
that class.

4. Explain the basic features of OOPs ?


OOPs has four basic features.

Abstraction : Abstraction is the process of exposing only the relevant data to the users without
showing unnecessary information
Polymorphism : I allows you to use an entity in multiple forms
Encapsulation : Prevents the data from unwanted access by binding of code and data in a single
unit called object
Inheritance : Promotes the reusability of code and eliminates the use of redundant code.

5. What are Abstract classes ?


An abstract class is a class that can not be instantiated and is always used as a base class.

Characteristics of an abstract class:

You can not instantiate an abstract class directly


You can have abstract as well as non abstract members in an abstract class
You must declare one abstract method in the abstract class
An abstract class is always public
An abstract class is declared using abstract keyword

6. Explain the features of an Interface


An Interface contains only the signature of methods
An Interface has no Implementation on its own
An Interface is used to implement multiple inheritance in code.
It defines a static set of methods and their arguments
Variables in Interface must be declared as public,static and final
Methods in an Interface must be declared as public and abstract
A class implementing an Interface must implement all of its method
An Interface can derive from more than one Interface

7. Difference between an abstract class and an Interface ?


Abstract Class Interface

A class can extend only one Abstract class A class can implement several interfaces

The member of an abstract class can be private and An Interface can only have public members
protected

Abstract classes should have subclasses Interfaces must have Implementations by


classes

Any class can extend an abstract class Only an Interface can extend another Interface

Methods in an abstract class can be abstract as well as All methods in an Interface should be abstract
concrete

There can be a constructor for Abstract class Interface does not have constructor

An abstract class can Implement methods Interfaces can not contain body of any of its
method

8. Explain different types of Inheritance


There are four types of Inheritance in Object oriented programming.

Single Inheritance : contains one base class and one derived class
Hierarchical Inheritance : Contains one base class and multiple derived classes of same base
class
Multilevel Inheritance : Contains a class derived from a derived class
Multiple Inheritance : Contains several base class and a derived class

9. What is Constructor?
C# constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the
object that is why it is known as constructor.
A constructor is a special method that is used to initialize an object. Every class has a constructor,if we
dont explicitly declare a constructor for any C# class the compiler builds a default constructor for that
class. A constructor does not have any return type. Constructors are responsible for object initialization
and memory allocation of its class.
There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type

You can read more on constructor here.

10. What is Destructor?


A Destructor is automatically invoked when an object is finally destroyed. The name of the Destructor is
same as class and prefixed with a tilde (~)

A Destructor is used to free the dynamic allocated memory and release the resources. You can
Implement a custom method that allows to control object destruction by calling the destructor.

Destructors don not have any return type


Destructors are always public
Destructors can not be overloaded

11. What is a Static Constructor?


Static constructor is used to initialize static data of a class. Compiler calls the static constructor before the
first instance is created.

No access specifier is required to define it


You can not pass parameters to static constructor
A class can have only one static constructor
It can access only static members of class
It is invoked only once, when the program execution begins

12. What is Method Overloading?


Method Overloading lets you have 2 methods with same name and different signature.
Overloading can be achieved:
-By changing the number of parameters used.
-By changing the order of parameters.
-By using different data types for the parameters.

13. What is Access Specifier?


An access specifier defines the scope and visibility of a class member. C# supports the following access
specifiers:

Public
Private
Protected
Internal
Protected internal

14. What is Encapsulation?


Encapsulation is a process of hiding the members from outside of class and implemented using
access specifiers
Encapsulation is also called as information hiding.
Encapsulation provides a way to preserve the integrity of state data. Rather than defining public
fields, private data fields should be defined.
Well-encapsulated class should hide its data and the details of how it operates on data from the
outside world. This is termed black box programming.
Using this,implementation of the method can be changed by the class author without breaking
any existing code making use of it.

15. What is the difference between Method Overloading and Method


Overriding?
Method Overloading Method Overriding

Method Overloading lets you have 2 methods with Method Overloading lets you have 2 methods with
same name and different signature same name and same signature

Overloading is called as compile time Overriding is called as run time polymorphism or late
polymorphism or early binding binding or dynamic polymorphism

Overloading can be achieved: Overriding can be achieved:


-By changing the number of parameters used. -Creating the method in a derived class with same
-By changing the order of parameters. name, same parameters and same return type as in
-By using different data types for the parameters. base class is called as method overriding

Method overloading can be overloaded in same Method overriding is only possible in derived class
class or in the child class. not within the same class where the method is
declared

Example: Example:

public class Methodoverloading Public class test

{ {

public int addition(int a, int b) //Two public virtual int addition()


int parameters with same method {
{ return 10;
return a + b; }
} }
public int addition(int a, int b,int c) public class Amount:test
//Three int Parameters with same method
{
{
public override int balance()
return a + b + c;
{
}
return 500;
public float addition(float a, float
b,float c,float d) //four float type }
Parameters with same method same as above }
two method
{
return a + b + c + d;
}
}

16. What is the difference between Abstraction and Encapsulation ?


Encapsulation is wrapping, just hiding properties and methods. Encapsulation is used for hide the code
and data in a single unit to protect the data from the outside the world. Class is the best example of
encapsulation. Abstraction refers to showing only the necessary details to the intended user.

17. What is Operator Overloading ?


Operator overloading is a technique by which operators used in a programming language are
implemented in user-defined types with customized logic that is based on the types of arguments passed.

Operator overloading facilitates the specification of user-defined implementation for operations wherein
one or both operands are of user-defined class or structure type. This helps user-defined types to behave
much like the fundamental primitive data types. Operator overloading is helpful in cases where the
operators used for certain types provide semantics related to the domain context and syntactic support as
found in the programming language. It is used for syntactical convenience, readability and maintainability

18. What is a Delegate ?


Delegates are type safe function pointer. It holds reference to a function.

The signature of delegates matches the signature of the function that it points to else you will get
compilation error.
Delegates are typesafe pointers because it points to a function and holds the signature of the function.
19. What is multicast Delegate ?
A multicast delegate is a delegate that has references to more than one function.When you inoke a
multicase delegate,all the functions the delegate is pointing to are also invoked.

There are 2 ways to create multicast delegate.

+ or += to register a method with the delegate


or -= to unregister a method with the delegate
A multicast delegate invokes the methods in invocation list in same order in which they are added.

20. What are Events ?


Events are user actions such as key press, clicks, mouse moves, etc., or some occurrence such as
system generated notifications. Applications need to respond to events when they occur.

21. What is the difference between Array and Collection?


Array Collection

You need to specify the size of an array at the The size of a collection can be adjusted dynamically as
time of its declaration.It can not be resized. per users requirement.It does not have fixed size

The member of an array should be of the same Collection can have elements of different types
data type

22. What is the difference between Shadowing and Overriding?


Shadowing:
1.You can shadow a base class member in the derived class by using the keyword Shadows.
2.The method signature, access level and return type of the shadowed member can be completely
different than the base class member.
3.A method or function of the base class is available to the child (derived) class without the use of the
overriding keyword.
4.The compiler hides the function or method of the base class. This concept is known as shadowing or
method hiding.
5.In the shadowing or method hiding, the child (derived) class has its own function, the same function is
also available in the base class.

Overriding:
1.Method overriding is an important feature of OOPS that allows us to re-write a base class function or
method with a different definition.
2.Overriding is also known as Dynamic Polymorphism because overriding is resolved at runtime.
3.The method signature, access level and return type of the hidden member has to be same as the base
class member
4.In other words both methods (base class method and derived class method) have the same name,
same number and same type of parameter in the same order with the same return type.
5.The overridden base method must be virtual, abstract or override.

You can look at C# implementation on Shadowing and Overriding here.

23. What is the difference between Class and Structure?


Class Structure

A Class is a reference type A Structure is a value type

By default, the members of a Class are private By default, the members of a Structure are public

Class supports Inheritance Structure does not support Inheritance

Class can contain constructor/destructor Structure does not require Constructor/Destructor

Variables of a Class can be assigned as null Structure members can not have null values

24. What is the similarities between Class and Structure?


Access specifiers are identically used in structure and classes to restrict the access of their data
and methods outside their body
Both can have constructors,methods, properties,fields, constants etc..
Both can implement Interfaces to use multiple-inheritance in code
Both can have Delegates and Events

25. What is Enum?


An enum is a distinct value typewith a set of named constants
It is declared by using keyword Enum
Every Enum type has an underlying type which can be any integral type except char. The default
underlying type is int.
The first enumerator has the value 0 by default and the value of each successive enumerator is
increased by 1
Enumeration bridge the gap between numbers and objects
26. What is a Nested Class?
Nested class is nothing but defining a class within another class.

Nested classes has the ability to specify private as an access modifier for the class itself.The use of the
private access modifier defines the intended accessibility of the class and prevents access from outside
the class.

27. What is an Indexer?


An Indexer is a member that enables an object to be indexed like Arrays.

28. What is Sealed keyword in C#?


You can disable inheritance by using the sealed keyword on a class or a method. When used on a class,
you cant derive other classes from it. When used on a method, derived classes cant override the
method.

29. What is a hashtable?


Hashtable is store multiple items and each of these items is associated with unique string key. Each item
can be accessed using the key associated with it.

30. What is Polymorphism and explain different types of


Polymrphism?
The word polymorphism means having many forms.
polymorphism is one interface, multiple functions. Polymorphism can be static or dynamic.

Static Polymrphism:
The mechanism of linking a function with an object during compile time is called early binding. It is also
called static binding. C# provides two techniques to implement static polymorphism. They are:

1.Function overloading
2.Operator overloading

Dynamic Polymorphism:
The mechanism of linking method to an object during run time is called late binding.It is also known as
run-time polymorphism. Method overriding helps to implement Dynamic Polymorphism.

Você também pode gostar