You are on page 1of 84

Interview Questions

ASP.NET

1. Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading


process. inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other
things.When an ASP.NET request is received (usually a file with .aspx extension),the ISAPI filter
aspnet_isapi.dll takes care of it by passing the request tothe actual worker process aspnet_wp.exe.
2. What’s the difference between Response.Write() andResponse.Output.Write()? The latter one
allows you to write formattedoutput.
3. What methods are fired during the page load? Init() - when the pageis instantiated, Load() -
when the page is loaded into server memory,PreRender() - the brief moment before the page is
displayed to the user asHTML, Unload() - when page finishes loading.
4. Where does the Web page belong in the .NET Framework class hierarchy?
System.Web.UI.Page
5. Where do you store the information about the user’s locale? System.Web.UI.Page.Culture
6. What’s the difference between Codebehind="MyCode.aspx.cs" andSrc="MyCode.aspx.cs"?
CodeBehind is relevant to Visual Studio.NET only.
7. What’s a bubbled event? When you have a complex control, like DataGrid, writing an event
processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble
up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents.
8. Suppose you want a certain ASP.NET function executed on MouseOver overa certain button.
Where do you add an event handler? It’s the Attributesproperty, the Add function inside that
property. So btnSubmit.Attributes.Add("onMouseOver","someClientCode();")
9. What data type does the RangeValidator control support? Integer,String and Date.
10. Explain the differences between Server-side and Client-side code? Server-side code runs on the
server. Client-side code runs in the clients’ browser.
11. What type of code (server or client) is found in a Code-Behind class? Server-side code.
12. Should validation (did the user enter a real date) occur server-side or client-side? Why?
Client-side. This reduces an additional request to the server to validate the users input.
13. What does the "EnableViewState" property do? Why would I want it on or off? It enables the
viewstate on the page. It allows the page to save the users input on a form.
14. What is the difference between Server.Transfer and Response.Redirect? Why would I choose
one over the other? Server.Transfer is used to post a form to another page. Response.Redirect is
used to redirect the user to another page or site.
15. Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?

• A DataSet can represent an entire relational database in memory, complete with tables,
relations, and views.
• A DataSet is designed to work without any continuing connection to the original data
source.
• Data in a DataSet is bulk-loaded, rather than being loaded on demand.
• There's no concept of cursor types in a DataSet.
• DataSets have no current record pointer You can use For Each loops to move through the
data.
• You can store many edits in a DataSet, and write them to the original data source in a
single operation.
• Though the DataSet is universal, other objects in ADO.NET come in different versions for
different data sources.
16. Can you give an example of what might be best suited to place in the Application_Start and
Session_Start subroutines? This is where you can set the specific variables for the Application
and Session objects.
17. If I’m developing an application that must accommodate multiple security levels though
secure login and my ASP.NET web application is spanned across three web-servers (using
round-robin load balancing) what would be the best approach to maintain login-in state for
the users? Maintain the login state security through a database.
18. Can you explain what inheritance is and an example of when you might use it? When you want
to inherit (use the functionality of) another class. Base Class Employee. A Manager class could be
derived from the Employee base class.
19. Whats an assembly? Assemblies are the building blocks of the .NET framework. Overview of
assemblies from MSDN
20. Describe the difference between inline and code behind. Inline code written along side the html
in a page. Code-behind is code written in a separate file and referenced by the .aspx page.
21. Explain what a diffgram is, and a good use for one? The DiffGram is one of the two XML
formats that you can use to render DataSet object contents to XML. For reading database data to an
XML file to be sent to a Web Service.
22. Whats MSIL, and why should my developers need an appreciation of it if at all? MSIL is the
Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL.
23. Which method do you invoke on the DataAdapter control to load your generated dataset with
data? The .Fill() method
24. Can you edit data in the Repeater control? No, it just reads the information from its data source
25. Which template must you provide, in order to display data in a Repeater control?
ItemTemplate
26. How can you provide an alternating color scheme in a Repeater control? Use the
AlternatingItemTemplate
27. What property must you set, and what method must you call in your code, in order to bind
the data from some data source to the Repeater control? You must set the DataSource property
and call the DataBind method.
28. What base class do all Web Forms inherit from? The Page class.
29. Name two properties common in every validation control? ControlToValidate property and
Text property.
30. What tags do you need to add within the asp:datagrid tags to bind columns manually? Set
AutoGenerateColumns Property to false on the datagrid tag
31. What tag do you use to add a hyperlink column to the DataGrid? <asp:HyperLinkColumn>
32. What is the transport protocol you use to call a Web service? SOAP is the preferred protocol.
33. True or False: A Web service can only be written in .NET? False
34. What does WSDL stand for? (Web Services Description Language)
35. Where on the Internet would you look for Web services? (http://www.uddi.org)
36. Which property on a Combo Box do you set with a column name, prior to setting the
DataSource, to display data in the combo box? DataTextField property
37. Which control would you use if you needed to make sure the values in two different controls
matched? CompareValidator Control
38. True or False: To test a Web service you must create a windows application or Web
application to consume this service? False, the webservice comes with a test page and it provides
HTTP-GET method to test.
39. How many classes can a single .NET DLL contain? It can contain many classes.
Hibernate and NHibernate

Hibernate is an ORM [Object-Relational Mapping] service used to develop persistent Java classes. On the
back of NHibernate, it's popularity has spread to the .NET space as well. This has proved of special interest
in IT shops that are working toward interoperability strategies that leverage the skills of developers who can
handle both .NET and Java problems.

NHibernate is a port of Hibernate Core for Java to the .NET Framework. It handles persisting plain .NET
objects to and from an underlying relational database. Given an XML description of your entities and
relationships, NHibernate automatically generates SQL for loading and storing the objects. Optionally, you
can describe your mapping metadata with attributes in your source code.

NHibernate supports transparent persistence, your object classes don't have to follow a restrictive
programming model. Persistent classes do not need to implement any interface or inherit from a special base
class. This makes it possible to design the business logic using plain .NET (CLR) objects and object-oriented
idiom.

Originally being a port of Hibernate 2.1, the NHibernate API is very similar to that of Hibernate. All
Hibernate knowledge and existing Hibernate documentation is therefore directly applicable to NHibernate

NHibernate key features:


Natural programming model - NHibernate supports natural OO idiom; inheritance, polymorphism,
composition and the .NET collections framework, including generic collections.

Native .NET - NHibernate API uses .NET conventions and idioms


Support for fine-grained object models - a rich variety of mappings for collections and dependent objects

No build-time bytecode enhancement - there's no extra code generation or bytecode processing steps in your
build procedure

The query options - NHibernate addresses both sides of the problem; not only how to get objects into the
database, but also how to get them out again

Custom SQL - specify the exact SQL that NHibernate should use to persist your objects. Stored procedures
are supported on Microsoft SQL Server.

Support for "conversations" - NHibernate supports long-lived persistence contexts, detach/reattach of


objects, and takes care of optimistic locking automatically

Free/open source - NHibernate is licensed under the LGPL (Lesser GNU Public License)

More detailes at official website :: http://www.hibernate.org/


ASP.NET 2.0 Interview Questions – Beginner Level
(Part 1)
The Q&A mentioned over here have been taken from forums, my colleagues and my own experience of
conducting interviews. I have tried to mention the contributor wherever possible. If you would like to
contribute, kindly use the Contact form. If you think that a credit for a contribution is missing
somewhere, kindly use the same contact form and I will do the needful.
Check out the other interview questions over here:
General .NET Interview Questions
.NET Framework Interview Questions
ASP.NET 2.0 Interview Questions - Intermediate Level
What is ASP.NET?
Microsoft ASP.NET is a server side technology that enables programmers to build dynamic Web sites,
web applications, and XML Web services. It is a part of the .NET based environment and is built on the
Common Language Runtime (CLR) . So programmers can write ASP.NET code using any .NET
compatible language.
What are the differences between ASP.NET 1.1 and ASP.NET 2.0?
A comparison chart containing the differences between ASP.NET 1.1 and ASP.NET 2.0 can be found
over here.
Which is the latest version of ASP.NET? What were the previous versions released?
The latest version of ASP.NET is 2.0. There have been 3 versions of ASP.NET released as of date. They
are as follows :
ASP.NET 1.0 – Released on January 16, 2002.
ASP.NET 1.1 – Released on April 24, 2003.
ASP.NET 2.0 – Released on November 7, 2005.
Additionally, ASP.NET 3.5 is tentatively to be released by the end of the 2007.
Explain the Event Life cycle of ASP.NET 2.0?
The events occur in the following sequence. Its best to turn on tracing(<% @Page Trace=”true”%>)
and track the flow of events :
PreInit – This event represents the entry point of the page life cycle. If you need to change the Master
page or theme programmatically, then this would be the event to do so. Dynamic controls are created
in this event.
Init – Each control in the control collection is initialized.
Init Complete* - Page is initialized and the process is completed.
PreLoad* - This event is called before the loading of the page is completed.
Load – This event is raised for the Page and then all child controls. The controls properties and view
state can be accessed at this stage. This event indicates that the controls have been fully loaded.
LoadComplete* - This event signals indicates that the page has been loaded in the memory. It also
marks the beginning of the rendering stage.
PreRender – If you need to make any final updates to the contents of the controls or the page, then
use this event. It first fires for the page and then for all the controls.
PreRenderComplete* - Is called to explicitly state that the PreRender phase is completed.
SaveStateComplete* - In this event, the current state of the control is completely saved to the
ViewState.
Unload – This event is typically used for closing files and database connections. At times, it is also
used for logging some wrap-up tasks.
The events marked with * have been introduced in ASP.NET 2.0.
You have created an ASP.NET Application. How will you run it?
With ASP.NET 2.0, Visual Studio comes with an inbuilt ASP.NET Development Server to test your
pages. It functions as a local Web server. The only limitation is that remote machines cannot access
pages running on this local server. The second option is to deploy a Web application to a computer
running IIS version 5 or 6 or 7.
Explain the AutoPostBack feature in ASP.NET?
AutoPostBack allows a control to automatically postback when an event is fired. For eg: If we have a
Button control and want the event to be posted to the server for processing, we can set AutoPostBack
= True on the button.
How do you disable AutoPostBack?
Hence the AutoPostBack can be disabled on an ASP.NET page by disabling AutoPostBack on all the
controls of a page. AutoPostBack is caused by a control on the page.
What are the different code models available in ASP.NET 2.0?
There are 2 code models available in ASP.NET 2.0. One is the single-file page and the other one is the
code behind page.
Which base class does the web form inherit from?
Page class in the System.Web.UI namespace.
Which are the new special folders that are introduced in ASP.NET 2.0?
There are seven new folders introduced in ASP.NET 2.0 :
\App_Browsers folder – Holds browser definitions(.brower) files which identify the browser and their
capabilities.
\App_Code folder – Contains source code (.cs, .vb) files which are automatically compiled when
placed in this folder. Additionally placing web service files generates a proxy class(out of .wsdl) and a
typed dataset (out of .xsd).
\App_Data folder – Contains data store files like .mdf (Sql Express files), .mdb, XML files etc. This
folder also stores the local db to maintain membership and role information.
\App_GlobalResources folder – Contains assembly resource files (.resx) which when placed in this
folder are compiled automatically. In earlier versions, we were required to manually use the resgen.exe
tool to compile resource files. These files can be accessed globally in the application.
\App_LocalResources folder – Contains assembly resource files (.resx) which can be used by a
specific page or control.
\App_Themes folder – This folder contains .css and .skin files that define the appearance of web
pages and controls.
\App_WebReferences folder – Replaces the previously used Web References folder. This folder
contains the .disco, .wsdl, .xsd files that get generated when accessing remote web services.
Explain the ViewState in ASP.NET?
Http is a stateless protocol. Hence the state of controls is not saved between postbacks. Viewstate is
the means of storing the state of server side controls between postbacks. The information is stored in
HTML hidden fields. In other words, it is a snapshot of the contents of a page.
You can disable viewstate by a control by setting the EnableViewState property to false.
What does the EnableViewState property signify?
EnableViewState saves the state of an object in a page between postbacks. Objects are saved in a
Base64 encoded string. If you do not need to store the page, turn it off as it adds to the page size.
There is an excellent article by Peter Bromberg to understand Viewstate in depth.
Explain the ASP.NET Page Directives?
Page directives configure the runtime environment that will execute the page. The complete list of
directives is as follows:
@ Assembly - Links an assembly to the current page or user control declaratively.
@ Control - Defines control-specific attributes used by the ASP.NET page parser and compiler and can
be included only in .ascx files (user controls).
@ Implements - Indicates that a page or user control implements a specified .NET Framework interface
declaratively.
@ Import - Imports a namespace into a page or user control explicitly.
@ Master - Identifies a page as a master page and defines attributes used by the ASP.NET page parser
and compiler and can be included only in .master files.
@ MasterType - Defines the class or virtual path used to type the Master property of a page.
@ OutputCache - Controls the output caching policies of a page or user control declaratively.
@ Page - Defines page-specific attributes used by the ASP.NET page parser and compiler and can be
included only in .aspx files.
@ PreviousPageType - Creates a strongly typed reference to the source page from the target of a
cross-page posting.
@ Reference - Links a page, user control, or COM control to the current page or user control
declaratively.
@ Register - Associates aliases with namespaces and classes, which allow user controls and custom
server controls to be rendered when included in a requested page or user control.
This list has been taken from here.
Explain the Validation Controls used in ASP.NET 2.0?
Validation controls allows you to validate a control against a set of rules. There are 6 different
validation controls used in ASP.NET 2.0.
RequiredFieldValidator – Checks if the control is not empty when the form is submitted.
CompareValidator – Compares the value of one control to another using a comparison operator (equal,
less than, greater than etc).
RangeValidator – Checks whether a value falls within a given range of number, date or string.
RegularExpressionValidator – Confirms that the value of a control matches a pattern defined by a
regular expression. Eg: Email validation.
CustomValidator – Calls your own custom validation logic to perform validations that cannot be handled
by the built in validators.
ValidationSummary – Show a summary of errors raised by each control on the page on a specific spot
or in a message box.
How do you indentify that the page is post back?
By checking the IsPostBack property. If IsPostBack is True, the page has been posted back.
What are Master Pages?
Master pages is a template that is used to create web pages with a consistent layout throughout your
application. Master Pages contains content placeholders to hold page specific content. When a page is
requested, the contents of a Master page are merged with the content page, thereby giving a
consistent layout.
How is a Master Page different from an ASP.NET page?
The MasterPage has a @Master top directive and contains ContentPlaceHolder server controls. It is
quiet similar to an ASP.NET page.
How do you attach an exisiting page to a Master page?
By using the MasterPageFile attribute in the @Page directive and removing some markup.
How do you set the title of an ASP.NET page that is attached to a Master Page?
By using the Title property of the @Page directive in the content page. Eg:
<@Page MasterPageFile="Sample.master" Title="I hold content" %>
What is a nested master page? How do you create them?
A Nested master page is a master page associated with another master page. To create a nested
master page, set the MasterPageFile attribute of the @Master directive to the name of the .master file
of the base master page.
What are Themes?
Themes are a collection of CSS files, .skin files, and images. They are text based style definitions and
are very similar to CSS, in that they provide a common look and feel throughout the website.
What are skins?
A theme contains one or more skin files. A skin is simply a text file with a .skin extension and contains
definition of styles applied to server controls in an ASP.NET page. For eg:
<asp:button runat="server" BackColor="blue" BorderColor="Gray" Font-Bold ="true"
ForeColor="white"/>
Defines a skin that will be applied to all buttons throughout to give it a consistent look and feel.
What is the difference between Skins and Css files?
Css is applied to HTML controls whereas skins are applied to server controls.
What is a User Control?
User controls are reusable controls, similar to web pages. They cannot be accessed directly.
Explain briefly the steps in creating a user control?
• Create a file with .ascx extension and place the @Control directive at top of the page.
• Included the user control in a Web Forms page using a @Register directive
What is a Custom Control?
Custom controls are compiled components that run on the server and that encapsulate user-interface
and other related functionality into reusable packages. They can include all the design-time features of
standard ASP.NET server controls, including full support for Visual Studio design features such as the
Properties window, the visual designer, and the Toolbox.
What are the differences between user and custom controls?
User controls are easier to create in comparison to custom controls, however user controls can be less
convenient to use in advanced scenarios.
User controls have limited support for consumers who use a visual design tool whereas custom controls
have full visual design tool support for consumers.
A separate copy of the user control is required in each application that uses it whereas only a single
copy of the custom control is required, in the global assembly cache, which makes maintenance easier.
A user control cannot be added to the Toolbox in Visual Studio whereas custom controls can be added
to the Toolbox in Visual Studio.
User controls are good for static layout whereas custom controls are good for dynamic layout.
Where do you store your connection string information?
The connection string can be stored in configuration files (web.config).
What is the difference between ‘Web.config’ and ‘Machine.config’?
Web.config files are used to apply configuration settings to a particular web application whereas
machine.config file is used to apply configuration settings for all the websites on a web server.
Web.config files are located in the application's root directory or inside a folder situated in a lower
hierarchy. The machine.config is located in the Windows directory
Microsoft.Net\Framework\Version\CONFIG.
There can be multiple web.config files in an application nested at different hierarchies. However there
can be only one machine.config file on a web server.
What is the difference between Server.Transfer and Response.Redirect?
Response.Redirect involves a roundtrip to the server whereas Server.Transfer conserves server
resources by avoiding the roundtrip. It just changes the focus of the webserver to a different page and
transfers the page processing to a different page.
Response.Redirect can be used for both .aspx and html pages whereas Server.Transfer can be used
only for .aspx pages.
Response.Redirect can be used to redirect a user to an external websites. Server.Transfer can be used
only on sites running on the same server. You cannot use Server.Transfer to redirect the user to a page
running on a different server.
Response.Redirect changes the url in the browser. So they can be bookmarked. Whereas
Server.Transfer retains the original url in the browser. It just replaces the contents of the previous
page with the new one.
What method do you use to explicitly kill a users session?
Session.Abandon().
What is a webservice?
Web Services are applications delivered as a service on the Web. Web services allow for programmatic
access of business logic over the Web. Web services typically rely on XML-based protocols, messages,
and interface descriptions for communication and access. Web services are designed to be used by
other programs or applications rather than directly by end user. Programs invoking a Web service are
called clients. SOAP over HTTP is the most commonly used protocol for invoking Web services.

C# Interview Questions

1. What’s the implicit name of the parameter that gets passed into the class’ set method? Value, and
its datatype depends on whatever variable we’re changing.

2. How do you inherit from a class in C#? Place a colon and then the name of the base class. Notice that
it’s double colon in C++.

3. Does C# support multiple inheritance? No, use interfaces instead.

4. When you inherit a protected class-level variable, who is it available to? Classes in the same
namespace.

5. Are private class-level variables inherited? Yes, but they are not accessible, so looking at it you can
honestly say that they are not inherited. But they are.

6. Describe the accessibility modifier protected internal. It’s available to derived classes and classes
within the same Assembly (and naturally from the base class it’s declared in).
7. C# provides a default constructor for me. I write a constructor that takes a string as a parameter,
but want to keep the no parameter one. How many constructors should I write? Two. Once you
write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself,
even if there’s no implementation in it.

8. What’s the top .NET class that everything is derived from? System.Object.

9. How’s method overriding different from overloading? When overriding, you change the method
behavior for a derived class. Overloading simply involves having a method with the same name within the
class.

10. What does the keyword virtual mean in the method definition? The method can be over-ridden.

11. Can you declare the override method static while the original method is non-static? No, you can’t,
the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword
override.

12. Can you override private virtual methods? No, moreover, you cannot access private methods in
inherited classes, have to be protected in the base class to allow any sort of access.

13. Can you prevent your class from being inherited and becoming a base class for some other
classes? Yes, that’s what keyword sealed in the class definition is for. The developer trying to derive from
your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. It’s the same
concept as final class in Java.

14. Can you allow class to be inherited, but prevent the method from being over-ridden? Yes, just
leave the class public and make the method sealed.

15. What’s an abstract class? A class that cannot be instantiated. A concept in C++ known as pure virtual
method. A class that must be inherited and have the methods over-ridden. Essentially, it’s a blueprint for a
class without any implementation.

16. When do you absolutely have to declare a class as abstract (as opposed to free-willed educated
choice or decision based on UML diagram)? When at least one of the methods in the class is abstract.
When the class itself is inherited from an abstract class, but not all base abstract methods have been over-
ridden.

17. What’s an interface class? It’s an abstract class with public abstract methods all of which must be
implemented in the inherited classes.

18. Why can’t you specify the accessibility modifier for methods inside the interface? They all must be
public. Therefore, to prevent you from getting the false impression that you have any freedom of choice,
you are not allowed to specify any accessibility, it’s public by default.

19. Can you inherit multiple interfaces? Yes, why not.

20. And if they have conflicting method names? It’s up to you to implement the method inside your own
class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if
similarly named methods from different interfaces expect different data, but as far as compiler cares you’re
okay.

21. What’s the difference between an interface and abstract class? In the interface all methods must be
abstract; in the abstract class some methods can be concrete. In the interface no accessibility modifiers
are allowed, which is ok in abstract classes.

22. How can you overload a method? Different parameter data types, different number of parameters,
different order of parameters.
23. If a base class has a bunch of overloaded constructors, and an inherited class has another bunch
of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary
base constructor? Yes, just place a colon, and then keyword base (parameter list to invoke the
appropriate constructor) in the overloaded constructor definition inside the inherited class.

24. What’s the difference between System.String and System.StringBuilder classes? System.String is
immutable; System.StringBuilder was designed with the purpose of having a mutable string where a
variety of operations can be performed.

25. What’s the advantage of using System.Text.StringBuilder over System.String? StringBuilder is


more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each
time it’s being operated on, a new instance is created.

26. Can you store multiple data types in System.Array? No.

27. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()? The first
one performs a deep copy of the array, the second one is shallow.

28. How can you sort the elements of the array in descending order? By calling Sort() and then
Reverse() methods.

29. What’s the .NET datatype that allows the retrieval of data by a unique key? HashTable.

30. What’s class SortedList underneath? A sorted HashTable.

31. Will finally block get executed if the exception had not occurred? Yes.

32. What’s the C# equivalent of C++ catch (…), which was a catch-all statement for any possible
exception? A catch block that catches the exception of type System.Exception. You can also omit the
parameter data type in this case and just write catch {}.

33. Can multiple catch blocks be executed? No, once the proper catch code fires off, the control is
transferred to the finally block (if there are any), and then whatever follows the finally block.

34. Why is it a bad idea to throw your own exceptions? Well, if at that point you know that an error has
occurred, then why not write the proper code to handle that error instead of passing a new Exception
object to the catch block? Throwing your own exceptions signifies some design flaws in the project.

35. What’s a delegate? A delegate object encapsulates a reference to a method. In C++ they were referred
to as function pointers.

36. What’s a multicast delegate? It’s a delegate that points to and eventually fires off several methods.

37. How’s the DLL Hell problem solved in .NET? Assembly versioning allows the application to specify not
only the library it needs to run (which was available under Win32), but also the version of the assembly.

38. What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command.

39. What’s a satellite assembly? When you write a multilingual or multi-cultural application in .NET, and
want to distribute the core application separately from the localized modules, the localized assemblies that
modify the core application are called satellite assemblies.

40. What namespaces are necessary to create a localized application? System.Globalization,


System.Resources.

41. What’s the difference between // comments, /* */ comments and /// comments? Single-line,
multi-line and XML documentation comments.
42. How do you generate documentation from the C# file commented properly with a command-line
compiler? Compile it with a /doc switch.

43. What’s the difference between and XML documentation tag? Single line code example and
multiple-line code example.

44. Is XML case-sensitive? Yes, so and are different elements.

45. What debugging tools come with the .NET SDK? CorDBG – command-line debugger, and DbgCLR –
graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C#
file using the /debug switch.

46. What does the This window show in the debugger? It points to the object that’s pointed to by this
reference. Object’s instance data is shown.

47. What does assert() do? In debug compilation, assert takes in a Boolean condition as a parameter, and
shows the error dialog if the condition is false. The program proceeds without any interruption if the
condition is true.

48. What’s the difference between the Debug class and Trace class? Documentation looks the same.
Use Debug class for debug builds, use Trace class for both debug and release builds.

49. Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The tracing dumps can be
quite verbose and for some applications that are constantly running you run the risk of overloading the
machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing
activities.

50. Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending
on the parameter passed to the constructor.

51. How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe process to the DbgClr
debugger.

52. What are three test cases you should go through in unit testing? Positive test cases (correct data,
correct output), negative test cases (broken or missing data, proper handling), exception test cases
(exceptions are thrown and caught properly).

53. Can you change the value of a variable while debugging a C# application? Yes, if you are
debugging via Visual Studio.NET, just go to Immediate window.

54. Explain the three services model (three-tier application). Presentation (UI), business (logic and
underlying code) and data (from storage or other sources).

55. What are advantages and disadvantages of Microsoft-provided data provider classes in
ADO.NET? SQLServer.NET data provider is high-speed and robust, but requires SQL Server license
purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft
Access and Informix, but it’s a .NET layer on top of OLE layer, so not the fastest thing in the world.
ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines.

56. What’s the role of the DataReader class in ADO.NET connections? It returns a read-only dataset
from the data source when the command is executed.

57. What is the wildcard character in SQL? Let’s say you want to query database with LIKE for all
employees whose name starts with La. The wildcard character is %, the proper query with LIKE would
involve ‘La%’.

58. Explain ACID rule of thumb for transactions. Transaction must be Atomic (it is one unit of work and
does not dependent on previous and following transactions), Consistent (data is either committed or roll
back, no “in-between” case where something has been updated and something hasn’t), Isolated (no
transaction sees the intermediate results of the current transaction), Durable (the values persist if the data
had been committed even if the system crashes right after).

59. What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory)
and SQL Server authentication (via Microsoft SQL Server username and passwords).

60. Which one is trusted and which one is untrusted? Windows Authentication is trusted because the
username and password are checked with the Active Directory, the SQL Server authentication is untrusted,
since SQL Server is the only verifier participating in the transaction.

61. Why would you use untrusted verificaion? Web Services might use it, as well as non-Windows
applications.

62. What does the parameter Initial Catalog define inside Connection String? The database name to
connect to.

63. What’s the data provider name to connect to Access database? Microsoft.Access.

64. What does Dispose method do with the connection object? Deletes it from the memory.

65. What is a pre-requisite for connection pooling? Multiple processes must agree that they will share the
same connection, where every parameter is the same, including the security settings.

66. What’s the implicit name of the parameter that gets passed into the class’ set method? Value,
and it’s datatype depends on whatever variable we’re changing.

67. How do you inherit from a class in C#? Place a colon and then the name of the base class.

68. Does C# support multiple inheritance? No, use interfaces instead.

69. When you inherit a protected class-level variable, who is it available to?Classes in the same
namespace.

70. Are private class-level variables inherited? Yes, but they are not accessible, so looking at it you can
honestly say that they are not inherited. But they are.

71. Describe the accessibility modifier protected internal. It’s available to derived classes and classes
within the same Assembly (and naturally from the base class it’s declared in).

72. C# provides a default constructor for me. I write a constructor that takes a string as a
parameter, but want to keep the no parameter one. How many constructors should I write? Two.
Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one
yourself, even if there’s no implementation in it.

73. What’s the top .NET class that everything is derived from? System.Object.

74. How’s method overriding different from overloading? When overriding, you change the method
behavior for a derived class. Overloading simply involves having a method with the same name within the
class.
75. What does the keyword virtual mean in the method definition? The method can be over-ridden.

76. Can you declare the override method static while the original method is non-static? No, you can’t,
the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword
override.

77. Can you override private virtual methods? No, moreover, you cannot access private methods in
inherited classes, have to be protected in the base class to allow any sort of access.

78. Can you prevent your class from being inherited and becoming a base class for some other
classes? Yes, that’s what keyword sealed in the class definition is for. The developer trying to derive from
your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. It’s the same
concept as final class in Java.

79. Can you allow class to be inherited, but prevent the method from being over-ridden? Yes, just
leave the class public and make the method sealed.

80. What’s an abstract class? A class that cannot be instantiated. A concept in C++ known as pure virtual
method. A class that must be inherited and have the methods over-ridden. Essentially, it’s a blueprint for a
class without any implementation.

81. When do you absolutely have to declare a class as abstract (as opposed to free-willed educated
choice or decision based on UML diagram)? When at least one of the methods in the class is abstract.
When the class itself is inherited from an abstract class, but not all base abstract methods have been over-
ridden.

82. What’s an interface class? It’s an abstract class with public abstract methods all of which must be
implemented in the inherited classes.

83. Why can’t you specify the accessibility modifier for methods inside the interface? They all must be
public. Therefore, to prevent you from getting the false impression that you have any freedom of choice,
you are not allowed to specify any accessibility, it’s public by default.

84. Can you inherit multiple interfaces? Yes, why not.

85. And if they have conflicting method names? It’s up to you to implement the method inside your own
class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if
similarly named methods from different interfaces expect different data, but as far as compiler cares you’re
okay.
86. What’s the difference between an interface and abstract class? In the interface all methods must be
abstract, in the abstract class some methods can be concrete. In the interface no accessibility modifiers are
allowed, which is ok in abstract classes.

87. How can you overload a method? Different parameter data types, different number of parameters,
different order of parameters.

88. If a base class has a bunch of overloaded constructors, and an inherited class has another bunch
of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary
base constructor? Yes, just place a colon, and then keyword base (parameter list to invoke the
appropriate constructor) in the overloaded constructor definition inside the inherited class.

89. What’s the difference between System.String and System.StringBuilder classes? System.String is
immutable, System.StringBuilder was designed with the purpose of having a mutable string where a
variety of operations can be performed.

90. Is it namespace class or class namespace? The .NET class library is organized into namespaces. Each
namespace contains a functionally related group of classes so natural namespace comes first.

91. General Questions

1.Does C# support multiple-inheritance? No. But you can use Interfaces.

2.Where is a protected class-level variable available? It is available to any sub-class derived from base class

3.Are private class-level variables inherited? Yes, but they are not accessible.

4.Describe the accessibility modifier “protected internal”.


It is available to classes that are within the same assembly and derived from the specified base class.

6.Which class is at the top of .NET class hierarchy? System.Object.

7.What does the term immutable mean?


The data value may not be changed.
Note: The variable value may be changed, but the original immutable data value was discarded and a new data
value was created in memory.

8.What’s the difference between System.String and System.Text.StringBuilder classes?


System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string
where a variety of operations can be performed.

9.What’s the advantage of using System.Text.StringBuilder over System.String?

StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are
immutable, so each time a string is changed, a new instance in memory is created.

10.Can you store multiple data types in System.Array? No.

11.What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?


The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array.
The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow
copy means the contents (each array element) contains references to the same object as the elements in the
original array. A deep copy (which neither of these methods performs) would create a new instance of each
element's object, resulting in a different, yet identacle object.
12.How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.

13.What’s the .NET collection class that allows an element to be accessed using a unique key? HashTable.

14.What class is underneath the SortedList class? A sorted HashTable.

15.Will the finally block get executed if an exception has not occurred? Yes.

16.What’s the C# syntax to catch any possible exception?


A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in
this case and just write catch {}.

17.Can multiple catch blocks be executed for a single try statement?


No. Once the proper catch block processed, control is transferred to the finally block .

18.Explain the three services model commonly know as a three-tier application?


Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources).

92. Class Questions

1.What is the syntax to inherit from a class in C#?


Place a colon and then the name of the base class. Example: class MyNewClass : MyBaseClass

2.Can you prevent your class from being inherited by another class?
Yes. The keyword “sealed” will prevent the class from being inherited.

3.Can you allow a class to be inherited, but prevent the method from being over-ridden?
Yes. Just leave the class public and make the method sealed.

4.What’s an abstract class?


A class that cannot be instantiated. An abstract class is a class that must be inherited and have the methods
overridden. An abstract class is essentially a blueprint for a class without any implementation.

5.When do you absolutely have to declare a class as abstract?

1. When the class itself is inherited from an abstract class, but not all base abstract methods have been
overridden.

2. When at least one of the methods in the class is abstract.

6.What is an interface class?


Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not
provide implementation. They are implemented by classes, and defined as separate entities from classes.

7.Why can’t you specify the accessibility modifier for methods inside the interface?
They all must be public, and are therefore public by default.

8.Can you inherit multiple interfaces? Yes. .NET does support multiple interfaces.

9.What happens if you inherit multiple interfaces and they have conflicting method names?
It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This
might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different
data, but as far as compiler cares you’re okay.

10. What’s the difference between an interface and abstract class?


In an interface class, all methods are abstract - there is no implementation. In an abstract class some methods can
be concrete. In an interface class, no accessibility modifiers are allowed. An abstract class may have accessibility
modifiers.

11. What is the difference between a Struct and a Class?


Structs are value-type variables and are thus saved on the stack, additional overhead but faster retrieval. Another
difference is that structs cannot inherit.

93. Method and Property Questions

1. What’s the implicit name of the parameter that gets passed into the set method/property of a class?
Value. The data type of the value parameter is defined by whatever data type the property is declared .

2. What does the keyword “virtual” declare for a method or property?


The method or property can be overridden.

3. How is method overriding different from method overloading?


When overriding a method, you change the behavior of the method for the derived class. Overloading a method
simply involves having another method with the same name within the class.

4. Can you declare an override method to be static if the original method is not static?
No. The signature of the virtual method must remain the same. (Note: Only the keyword virtual is changed to
keyword override)

5. What are the different ways a method can be overloaded?


Different parameter data types, different number of parameters, different order of parameters.

6. If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded
constructors; can you enforce a call from an inherited constructor to a specific base constructor?
Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the
overloaded constructor definition inside the inherited class.

94. Events and Delegates

1. What’s a delegate? A delegate object encapsulates a reference to a method.

2. What’s a multicast delegate?


A delegate that has multiple handlers assigned to it. Each assigned handler (method) is called.

3. What’s the implicit name of the parameter that gets passed into the class’ set method?
Value, and it’s datatype depends on whatever variable we’re changing.

4. How do you inherit from a class in C#? Place a colon and then the name of the base class.

5. Does C# support multiple inheritance? No, use interfaces instead.

6. When you inherit a protected class-level variable, who is it available to? Classes in the same namespace.

7. Are private class-level variables inherited?


Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited.

8. Describe the accessibility modifier protected internal.?


It’s available to derived classes and classes within the same Assembly (and naturally from the base class it’s
declared in).

9. C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to
keep the no parameter one. How many constructors should I write?
Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one
yourself, even if there’s no implementation in it.

10. What’s the top .NET class that everything is derived from?
System.Object.

11. How’s method overriding different from overloading?


When overriding, you change the method behavior for a derived class. Overloading simply involves having a
method with the same name within the class.

12. What does the keyword virtual mean in the method definition? The method can be over-ridden.
13. Can you declare the override method static while the original method is non-static?
No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to
keyword override.

14. Can you override private virtual methods?


No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to
allow any sort of access.

15. Can you prevent your class from being inherited and becoming a base class for some other classes?
Yes, that’s what keyword sealed in the class definition is for. The developer trying to derive from your class will get
a message: cannot inherit from Sealed class WhateverBaseClassName.
It’s the same concept as final class in Java.

16. Can you allow class to be inherited, but prevent the method from being over-ridden?
Yes, just leave the class public and make the method sealed.

17. What’s an abstract class?


A class that cannot be instantiated. A concept in C++ known as pure virtual method. A class that must be inherited
and have the methods over-ridden.
Essentially, it’s a blueprint for a class without any implementation.

18. When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or
decision based on UML diagram)?
When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class,
but not all base abstract methods have been over-ridden.

19. What’s an interface class?


It’s an abstract class with public abstract methods all of which must be implemented in the inherited classes.

20. Why can’t you specify the accessibility modifier for methods inside the interface?
They all must be public. Therefore, to prevent you from getting the false impression that you have any freedom of
choice, you are not allowed to specify any accessibility, it’s public by default.

21. Can you inherit multiple interfaces?Yes, why not.

22. And if they have conflicting method names?


It’s up to you to implement the method inside your own class, so implementation is left entirely up to you.
This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect
different data, but as far as compiler cares you’re okay.

23. What’s the difference between an interface and abstract class?


In the interface all methods must be abstract, in the abstract class some methods can be concrete. In the interface
no accessibility modifiers are allowed, which is ok in abstract classes.

24. How can you overload a method?


Different parameter data types, different number of parameters, different order of parameters.

25. If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded
constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor?
Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the
overloaded constructor definition inside the inherited class.

26. What’s the difference between System.String and System.StringBuilder classes?


System.String is immutable, System.StringBuilder was designed with the purpose of having a mutable string where
a variety of operations can be performed.

27. Is it namespace class or class namespace?


The .NET class library is organized into namespaces. Each namespace contains a functionally related group of
classes so natural namespace comes first.
FROM GLOBALSHIKSHA.COM

ASP.NET Interview Questions with Answers - Set 1

How many languages .NET is supporting now?


When .NET was introduced it came with several languages. VB.NET, C#, COBOL and Perl, etc. The site
DotNet Languages. Net says 44 languages are supported.

How is .NET able to support multiple languages?


A language should comply with the Common Language Runtime standard to become a .NET language. In
.NET, code is compiled to Microsoft Intermediate Language (MSIL for short). This is called as Managed
Code. This Managed code is run in .NET environment. So after compilation to this IL the language is not a
barrier. A code can call or use a function written in another language.

How ASP .NET different from ASP?


Scripting is separated from the HTML, Code is compiled as a DLL, and these DLLs can be executed on the
server.

What is smart navigation?


The cursor position is maintained when the page gets refreshed due to the server side validation and the page
gets refreshed.

What is view state?


The web is stateless. But in ASP.NET, the state of a page is maintained in the in the page itself
automatically. How? The values are encrypted and saved in hidden controls. this is done automatically by the
ASP.NET. This can be switched off / on for a single control.

How do you validate the controls in an ASP .NET page?


Using special validation controls that are meant for this. We have Range Validator, Email Validator.

Can the validation be done in the server side? Or this can be done only in the Client side?
Client side is done by default. Server side validation is also possible. We can switch off the client side and
server side can be done.

ASP.NET Interview Questions with Answers - Set 2

Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe


in the page loading process.
Ans : inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things.When
an ASP.NET request is received (usually a file with .aspx extension),the ISAPI filter aspnet_isapi.dll takes
care of it by passing the request tothe actual worker process aspnet_wp.exe..

What's the difference between Response.Write() and Response.Output.Write()?


Ans : The latter one allows you to write formatted output..

What methods are fired during the page load?


Ans : Init() - when the pageis instantiated, Load() - when the page is loaded into server memory,PreRender()
- the brief moment before the page is displayed to the user asHTML, Unload() - when page finishes loading..

Where does the Web page belong in the .NET Framework class hierarchy?
System.Web.UI.Page

Where do you store the information about the user's locale?


System.Web.UI.Page.Culture .

Suppose you want a certain ASP.NET function executed on MouseOver over a


certain button. Where do you add an event handler?
It's the Attributesproperty, the Add function inside that property. So
btnSubmit.Attributes.Add("onMouseOver","someClientCode();") A simple?Javascript:ClientCode();? in the
button control of the .aspx page will attach the handler (javascript function)to the onmouseover event.

ASP.NET Interview Questions with Answers - Set 3

Where would you use an iHTTPModule, and what are the limitations of any
approach you might take in implementing one?
Ans : One of ASP.NET's most useful features is the extensibility of the HTTP pipeline, the path that data
takes between client and server. You can use them to extend your ASP.NET applications by adding pre- and
post-processing to each HTTP request coming into your application. For example, if you wanted custom
authentication facilities for your application, the best technique would be to intercept the request when it
comes in and process the request in a custom HTTP module..

Explain what a diffgram is and a good use for one?


A DiffGram is an XML format that is used to identify current and original versions of data elements. The
DataSet uses the DiffGram format to load and persist its contents, and to serialize its contents for transport
across a network connection. When a DataSet is written as a DiffGram, it populates the DiffGram with all
the necessary information to accurately recreate the contents, though not the schema, of the DataSet,
including column values from both the Original and Current row versions, row error information, and row
order..

What's the difference between the System.Web.UI.WebControls.DataGrid and and


System.Windows.Forms.DataGrid?
Ans : The Web UI control does not inherently support master-detail data structures. As with other Web
server controls, it does not support two-way data binding. If you want to update data, you must write code to
do this yourself. You can only edit one row at a time. It does not inherently support sorting, although it raises
events you can handle in order to sort the grid contents. You can bind the Web Forms DataGrid to any object
that supports the IEnumerable interface. The Web Forms DataGrid control supports paging. It is easy to
customize the appearance and layout of the Web Forms DataGrid control as compared to the Windows
Forms one..

How do you display an editable drop-down list?


Ans : Displaying a drop-down list requires a template column in the grid. Typically, the ItemTemplate
contains a control such as a data-bound Label control to show the current value of a field in the record. You
then add a drop-down list to the EditItemTemplate. In Visual Studio, you can add a template column in the
Property builder for the grid, and then use standard template editing to remove the default TextBox control
from the EditItemTemplate and drag a DropDownList control into it instead. Alternatively, you can add the
template column in HTML view. After you have created the template column with the drop-down list in it,
there are two tasks. The first is to populate the list. The second is to preselect the appropriate item in the list ?
for example, if a book's genre is set to ?fiction,? when the drop-down list displays, you often want ?fiction?
to be preselected.

How do you check whether the row data has been changed?
Ans : The definitive way to determine whether a row has been dirtied is to handle the changed event for the
controls in a row. For example, if your grid row contains a TextBox control, you can respond to the control's
TextChanged event. Similarly, for check boxes, you can respond to a CheckedChanged event. In the handler
for these events, you maintain a list of the rows to be updated. Generally, the best strategy is to track the
primary keys of the affected rows. For example, you can maintain an ArrayList object that contains the
primary keys of the rows to update.

ASP.NET Interview Questions with Answers - Set 4

What do you know about .NET assemblies?


Assemblies are the smallest units of versioning and deployment in the .NET application. Assemblies are also
the building blocks for programs such as Web services, Windows services, serviced components, and .NET
remoting applications.

What's the difference between private and shared assembly?


Ans : Private assembly is used inside an application only and does not have to be identified by a strong
name. Shared assembly can be used by multiple applications and has to have a strong name..

What's a strong name?


Ans : A strong name includes the name of the assembly, version number, culture identity, and a public key
token..

How can you tell the application to look for assemblies at the locations other than its own install?
Ans : Use the directive in the XML .config file for a given application.
should do the trick. Or you can add additional search paths in the Properties box of the deployed application..

How can you debug failed assembly binds?


Ans : Use the Assembly Binding Log Viewer (fuslogvw.exe) to find out the paths searched..

Where are shared assemblies stored?


Ans : Global Assembly Cache..

How can you create a strong name for a .NET assembly?


With the help of Strong Name tool (sn.exe)..

Where's global assembly cache located on the system?


Ans : Usually C:\winnt\assembly or C:\windows\assembly..

Can you have two files with the same file name in GAC?
Ans : GAC is a very special folder, and while normally you would not be able to place two files with the
same name into a Windows folder, GAC differentiates by version number as well, so it's possible for
MyApp.dll and MyApp.dll to co-exist in GAC if the first one is version 1.0.0.0 and the second one is 1.1.0.0.
ASP.NET Interview Questions with Answers - Set 5

What is delay signing?


Ans : Delay signing allows you to place a shared assembly in the GAC by signing the assembly with just the
public key. This allows the assembly to be signed with the private key at a later stage, when the development
process is complete and the component or assembly is ready to be deployed. This process enables developers
to work with shared assemblies as if they were strongly named, and it secures the private key of the signature
from being accessed at different stages of development..

What are the authentication modes in ASP.NET?


Ans : None, Windows, Forms and Passport..

Are the actual permissions for the application defined at run-time or compile-time?
Ans : The CLR computes actual permissions at runtime based on code group membership and the calling
chain of the code..

What's a code group?


Ans : A code group is a set of assemblies that share a security context..

What's the difference between authentication and authorization?


Ans : Authentication happens first. You verify user's identity based on credentials. Authorization is making
sure the user only gets access to the resources he has credentials for..

What are the authentication modes in ASP.NET?


Ans : None, Windows, Forms and Passport.

Explain the differences between Server-side and Client-side code?


Ans : Server side scripting means that all the script will be executed by the server and interpreted as needed.
ASP doesn't have some of the functionality like sockets, uploading, etc. For these you have to make a custom
component usually in VB or VC++. Client side scripting means that the script will be executed immediately
in the browser such as form field validation, clock, email validation, etc. Client side scripting is usually done
in VBScript or JavaScript. Download time, browser compatibility, and visible code - since JavaScript and
VBScript code is included in the HTML page, then anyone can see the code by viewing the page source.
Also a possible security hazards for the client computer

ASP.NET Interview Questions with Answers - Set 6

Can you explain what inheritance is and an example of when you might use it?
Ans : Inheritance is a fundamental feature of an object oriented system and it is simply the ability to inherit
data and functionality from a parent object. Rather than developing new objects from scratch, new code can
be based on the work of other programmers, adding only new features that are needed..

What's an assembly?
Ans : Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit
of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a
collection of types and resources that are built to work together and form a logical unit of functionality. An
assembly provides the common language runtime with the information it needs to be aware of type
implementations. To the runtime, a type does not exist outside the context of an assembly..

Describe the difference between inline and code behind - which is best in a loosely coupled solution?
Ans : ASP.NET supports two modes of page development: Page logic code that is written inside "script
runat=server" blocks within an .aspx file and dynamically compiled the first time the page is requested on the
server. Page logic code that is written within an external class that is compiled prior to deployment on a
server and linked "behind" the .aspx file at run time..

Explain what a diffgram is, and a good use for one?


Ans : A DiffGram is an XML format that is used to identify current and original versions of data elements.
The DataSet uses the DiffGram format to load and persist its contents, and to serialize its contents for
transport across a network connection. When a DataSet is written as a DiffGram, it populates the DiffGram
with all the necessary information to accurately recreate the contents, though not the schema, of the DataSet,
including column values from both the Original and Current row versions, row error information, and row
order.

ASP.NET Interview Questions set 1


1)Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process?

inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received (usually a
file with .aspx extension), the ISAPI filter aspnet_isapi.dll takes care of it by passing the request tothe actual worker process aspnet_wp.exe.

2)What’s the difference between Response.Write() andResponse.Output.Write()?


Response.Output.Write() allows you to write formatted output.

3)What methods are fired during the page load?

Init() - when the page is instantiated


Load() - when the page is loaded into server memory
PreRender() - the brief moment before the page is displayed to the user as HTML
Unload() - when page finishes loading.

4)When during the page processing cycle is ViewState available?

After the Init() and before the Page_Load(), or OnLoad() for a control.

5)What namespace does the Web page belong in the .NET Framework class hierarchy?

System.Web.UI.Page

6)Where do you store the information about the user’s locale?

System.Web.UI.Page.Culture

7)What’s the difference between Codebehind="MyCode.aspx.cs" andSrc="MyCode.aspx.cs"?

CodeBehind is relevant to Visual Studio.NET only.

8)What’s a bubbled event?

When you have a complex control, like DataGrid, writing an event processing routine for each object (cell, button, row, etc.) is quite tedious. The
controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents.

9)Suppose you want a certain ASP.NET function executed on MouseOver for a


certain button. Where do you add an event handler?

Add an OnMouseOver attribute to the button. Example: btnSubmit.Attributes.Add("onmouseover","someClientCodeHere();");

10)What data types do the RangeValidator control support?

Integer, String, and Date.


ASP.NET Interview Questions set 2
Question:-How many types of cookies are there in .NET ?
Answer: Two type of cookeies.
a) single valued eg request.cookies(”UserName”).value=”dotnetquestion”
b)Multivalued cookies. These are used in the way collections are used example
request.cookies(”CookiName”)(”UserName”)=”dotnetquestionMahesh”
request.cookies(”CookiName”)(”UserID”)=”interview?

Question: What is Finalizer in .NET define Dispose and Finalize ?


Answer: We can say that Finalizer are the methods that's helps in cleanp the code that is executed before object is garbage collected .The process
is called finalization . There are two methods of finalizer Dispose and Finalize .There is little diffrenet between two of this method .
When we call Dispose method is realse all the resources hold by an object as well as all the resorces hold by the parent object.When we call
Dispose method it clean managed as well as unmanaged resources.
Finalize methd also cleans resources but finalize call dispose clears only the unmanged resources because in finalization the garbase collecter
clears all the object hold by managed code so finalization fails to prevent thos one of methd is used that is: GC.SuppressFinalize.

Question: Define SMTPclient class in DotNet framework class libarary ?


Answer: Each classes in dotnet framework inclue some properties,method and events.These properties ,methods and events are member of a
class.SMTPclient class mainly concern with sending mail.This class contain the folling member.
Properties:-
Host:-The name or IP address of email server.
Port:-Port that is use when sending mail.
Methods:-
Send:-Enables us to send email synchronously.
SendAsynchronous:-Enables us to send an email asynchronously.
Event:-
SendCompleted:-This event raised when an asynchronous send opertion completes.

Question: When we get Error 'HTTP 502 Proxy Error' ?


Answer: We get this error when we execute ASP.NET Web pages in Visual Web Developer Web server, because the URL randomly select port
number and proxy servers did not recognize the URL and return this error. To resolve this problem we have to change settings in Internet
Explorer to bypass the proxy server for local addresses, so that the request is not sent to the proxy.

Question: What is late binding ?


Answer: When code interacts with an object dynamically at runtime .because our code literally doesnot care what type of object it is interacting
and with the methods thats are supported by object and with the methods thats are supported by object .The type of object is not known by the
IDE or compiler ,no Intellisense nor compile-time syntax checking is possible but we get unprecedented flexibilty in exchange.if we enable strict
type checking by using option strict on at the top of our code modules ,then IDE and compiler will enforce early binding behaviour .By default
Late binding is done.

Question:-What is Com Marshler and its importance in .NET ?


Answer: Com Marshler is one of useful component of CLR. Its Task is to marshal data between Managed and Unmanaged environment .It helps
in representation of data accross diffrenet execution enviroment.It performs the conversion of data format between manage and unmanaged
code.By the helps of Com Marshlar CLR allows manage code to interoperate with unmanaged code.
Question: What is CSU and its description ?
Answer: CSU stands for comma separate values also called comma delimited.It is plain text file which stores spreadsheets or basic datatype in
very simple format.One record in each line and each field separted with comma's it is often used to transfer large ammount spreadsheet data or
database information between program.

Question: The IHttpHandler and IHttpHandlerFactory interfaces ?


Answer: The IHttpHandler interface is implemented by all the handlers. The interface consists of one property called IsReusable. The IsReusable
property gets a value indicating whether another request can use the IHttpHandler instance. The method ProcessRequest() allows you to process
the current request. This is the core place where all your code goes. This method receives a parameter of type HttpContext using which you can
access the intrinsic objects such as Request and Response. The IHttpHandlerFactory interface consists of two methods - GetHandler and
ReleaseHandler. The GetHandler() method instantiates the required HTTP handler based on some condition and returns it back to ASP.NET. The
ReleaseHandler() method allows the factory to reuse an existing handler.

ASP.NET Interview Questions set 3


Question: what is Viewstate?
Answer:View state is used by the ASP.NET page framework to automatically save the values of the page and of each control just prior to
rendering to the page. When the page is posted, one of the first tasks performed by page processing is to restore view state.
State management is the process by which you maintain state and page information over multiple requests for the same or different pages.
Client-side options are:* The ViewState property * Query strings
* Hidden fields * Cookies

Server-side options are:* Application state * Session state * DataBase

Use the View State property to save data in a hidden field on a page. Because ViewState stores data on the page, it is limited to items that can be
serialized. If you want to store more complex items in View State, you must convert the items to and from a string.
ASP.NET provides the following ways to retain variables between requests:
Context.Handler object Use this object to retrieve public members of one Web form’s class from a subsequently displayed Web form.
Query strings Use these strings to pass information between requests and responses as part of the Web address. Query strings are visible to the
user, so they should not contain secure information such as passwords.
Cookies Use cookies to store small amounts of information on a client. Clients might refuse cookies, so your code has to anticipate that
possibility.
View state ASP.NET stores items added to a page’s ViewState property as hidden fields on the page.
Session state Use Session state variables to store items that you want keep local to the current session (single user).
Application state Use Application state variables to store items that you want be available to all users of the application.
Question: DOTNET PAGE LIFECYCLE ?
Answer: While excuting the page, it will go under the fallowing steps(or fires the events) which collectivly known as Page Life cycle.
Page_Init -- Page Initialization
LoadViewState -- View State Loading
LoadPostData -- Postback data processing
Page_Load -- Page Loading
RaisePostDataChangedEvent -- PostBack Change Notification
RaisePostBackEvent -- PostBack Event Handling
Page_PreRender -- Page Pre Rendering Phase
SaveViewState -- View State Saving
Page_Render -- Page Rendering
Page_UnLoad -- Page Unloading

Question: What is Satellite Assemblies ?


Answer: Satellite assemblies are often used to deploy language-specific resources for an application. These language-specific assemblies work in
side-by-side execution because the application has a separate product ID for each language and installs satellite assemblies in a language-specific
subdirectory for each language. When uninstalling, the application removes only the satellite assemblies associated with a given language and
.NET Framework version. No core .NET Framework files are removed unless the last language for that .NET Framework version is being
removed. For example, English and Japanese editions of the .NET Framework version 1.1 share the same core files. The Japanese .NET
Framework version 1.1 adds satellite assemblies with localized resources in a \ja subdirectory. An application that supports the .NET Framework
version 1.1, regardless of its language, always uses the same core runtime files.

Question: What is CAS ?


Answer:CAS: CAS is the part of the .NET security model that determines whether or not a piece of code is allowed to run, and what resources it
can use when it is running. For example, it is CAS that will prevent a .NET web applet from formatting your hard disk. How does CAS work?
The CAS security policy revolves around two key concepts - code groups and permissions. Each .NET assembly is a member of a particular code
group, and each code group is granted the permissions specified in a named permission set. For example, using the default security policy, a
control downloaded from a web site belongs to the 'Zone - Internet' code group, which adheres to the permissions defined by the 'Internet' named
permission set. (Naturally the 'Internet' named permission set represents a very restrictive range of permissions.)

Question: Automatic Memory Management ?


Answer: Automatic Memory Management: From a programmer's perspective, this is probably the single biggest benefit of the .NET Framework.
No, I'm not kidding. Every project I've worked on in my long career of DOS and Windows development has suffered at some point from memory
management issues. Proper memory management is hard. Even very good programmers have difficulty with it. It's entirely too easy for a small
mistake to cause a program to chew up memory and crash, sometimes bringing the operating system to a screeching halt in the process.

Programmers understand that they're responsible for releasing any memory that they allocate, but they're not very good at actually doing it. In
addition, functions that allocate memory as a side effect abound in the Windows API and in the C runtime library. It's nearly impossible for a
programmer to know all of the rules. Even when the programmer follows the rules, a small memory leak in a support library can cause big
problems if called enough.

The .NET Framework solves the memory management problems by implementing a garbage collector that can keep track of allocated memory
references and release the memory when it is no longer referenced. A large part of what makes this possible is the blazing speed of today's
processors. When you're running a 2 GHz machine, it's easy to spare a few cycles for memory management. Not that the garbage collector takes a
huge number of cycles--it's incredibly efficient.
The garbage collector isn't perfect and it doesn't solve the problem of mis-managing other scarce resources (file handles, for example), but it
relieves programmers from having to worry about a huge source of bugs that trips almost everybody up in other programming environments.
On balance, automatic memory management is a huge win in almost every situation.
ASP.NET Interview Questions set 5
1.What are the main differences between asp and asp.net?

ASP 3.0

• Supports VBScript and JavaScript


o scripting languages are limited in scope
o interpreted from top to bottom each time the page is loaded
• Files end with *.asp extension
• 5 objects: Request, Response, Server, Application, Session
• Queried databases return recordsets
• Uses conventional HTML forms for data collection

ASP .NET

• Supports a number of languages including Visual Basic, C#, and JScript


o code is compiled into .NET classes and stored to speed up multiple hits on a page
o object oriented and event driven makes coding web pages more like traditional applications
• Files end with *.aspx extension
• .NET contains over 3400 classes
• XML-friendly data sets are used instead of recordsets
• Uses web forms that look like HTML forms to the client, but add much functionality due to server-side
coding
• Has built-in validation objects
• Improved debugging feature (great news for programmers)
• ASP .NET controls can be binded to a data source, including XML recordsets
Source: mikekissman.com

2. What is a user control?


• An ASP.NET user control is a group of one or more server controls or static HTML elements that
encapsulate a piece of functionality. A user control could simply be an extension of the functionality of an
existing server control(s) (such as an image control that can be rotated or a calendar control that stores the
date in a text box). Or, it could consist of several elements that work and interact together to get a job done
(such as several controls grouped together that gather information about a user's previous work experience).
Source: 15seconds.com

3. What are different types of controls available in ASP.net?


• HTML server controls HTML elements exposed to the server so you can program them. HTML server
controls expose an object model that maps very closely to the HTML elements that they render.
• Web server controls Controls with more built-in features than HTML server controls. Web server controls
include not only form-type controls such as buttons and text boxes, but also special-purpose controls such as
a calendar. Web server controls are more abstract than HTML server controls in that their object model does
not necessarily reflect HTML syntax.
• Validation controls Controls that incorporate logic to allow you to test a user's input. You attach a
validation control to an input control to test what the user enters for that input control. Validation controls are
provided to allow you to check for a required field, to test against a specific value or pattern of characters, to
verify that a value lies within a range, and so on.
• User controls Controls that you create as Web Forms pages. You can embed Web Forms user controls in
other Web Forms pages, which is an easy way to create menus, toolbars, and other reusable elements.
• Note You can also create output for mobile devices. To do so, you use the same ASP.NET page
framework, but you create Mobile Web Forms instead of Web Forms pages and use controls specifically
designed for mobile devices.
Source: MSDN

4. What are the validation controls available in ASP.net?


Type of validation Control to use
Description
Required entry RequiredFieldValidator Ensures that the user does not skip an entry.
Comparison to a value CompareValidator Compares a user's entry against a constant value, or against a
property value of another control, using a comparison operator (less than, equal, greater than, and so on).
Range checking RangeValidator Checks that a user's entry is between specified lower and upper boundaries.
You can check ranges within pairs of numbers, alphabetic characters, and dates.
Pattern matching RegularExpressionValidator Checks that the entry matches a pattern defined by a regular
expression. This type of validation allows you to check for predictable sequences of characters, such as those
in social security numbers, e-mail addresses, telephone numbers, postal codes, and so on.
User-defined CustomValidator Checks the user's entry using validation logic that you write yourself. This
type of validation allows you to check for values derived at run time.

5. How will you upload a file to IIS in Asp and how will you do the same in ASP.net?
First of all, we need a HTML server control to allow the user to select the file. This is nothing but the same
old one. This will give you the textbox and a browse button. Once you have this, the user can select any file
from their computer (or even from a network). Then, in the Server side, we need the following line to save
the file to the Web Server.

myFile.PostedFile.SaveAs ("DestinationPath")

Note: The Form should have the following ENC Type

6. What is Attribute Programming? What are attributes? Where are they used?
Attributes are a mechanism for adding metadata, such as compiler instructions and other data about your
data, methods, and classes, to the program itself. Attributes are inserted into the metadata and are visible
through ILDasm and other metadata-reading tools. Attributes can be used to identify or use the data at
runtime execution using .NET Reflection.
Source: OnDotNet.com

7. What is the difference between Data Reader & Dataset?


Data Reader is connected, read only forward only record set.
Dataset is in memory database that can store multiple tables, relations and constraints; moreover dataset is
disconnected and is not aware of the data source.

8. What is the difference between server side and client side code?
Server code is executed on the web server where as the client code is executed on the browser machine.

9. Why would you use “EnableViewState” property? What are the disadvantages?
EnableViewState allows me to retain the values of the controls properties across the requests in the same
session. It hampers the performance of the application.

10. What is the difference between Server. Transfer and Response. Redirect?
The Transfer method allows you to transfer from inside one ASP page to another ASP page. All of the state
information that has been created for the first (calling) ASP page will be transferred to the second (called)
ASP page. This transferred information includes all objects and variables that have been given a value in an
Application or Session scope, and all items in the Request collections. For example, the second ASP page
will have the same SessionID as the first ASP page.

When the second (called) ASP page completes its tasks, you do not return to the first (calling) ASP page. All
these happen on the server side browser is not aware of this.
The redirect message issue HTTP 304 to the browser and causes browser to got the specified page. Hence
there is round trip between client and server. Unlike transfer, redirect doesn’t pass context information to the
called page.

ASP.NET Interview Questions set 6

1. What is the difference between Application_start and Session_start?


Application_start gets fired when an application receive the very first request.
Session_start gets fired for each of the user session.

2. What is inheritance and when would you use inheritance?


The concept of child class inheriting the behavior of the parent is called inheritance.
If there are many classes in an application that have some part of their behavior common among all ,
inheritance would be used.

3. What is the order of events in a web form?


1. Init 2. Load 3. Cached post back events 4. Prerender 5. Unload

4. Can you edit Data in repeater control? No

5. Which template you must provide to display data in a repeater control? Item Template

6. How can you provide an alternating color scheme in a Data Grid?


Use ALTERNATINGITEMSTYLE and ITEMSTYLE, attributes or Templates

7. Is it possible to bind a data to Textbox? Yes

8. What method I should call to bind data to control? Bind Data ()

9. How can I kill a user session? Call session. abandon & Data Caching

ASP.NET Interview Questions set 7


1. Which is the common property among all the validation controls? ControlToValidate

2. How do you bind a data grid column manually? Use BoundColumn tag.

3. Web services can only be written in .NET, true or false? False

4. What does WSDL, UDDI stands for?


Web Service Description Language & Universal Description Discovery and Integration

5. How can you make a property read only? (C#) Use key word Read Only
5. Which validation control is used to match values in two controls? Compare Validation control.

6. To test a Web Service I must create either web application or windows application. True or false? False

7. How many classes can a single .NET assembly contains? Any number

8. What are the data types available in JavaScript? Object is the only data type available.

9. Is it possible to share session information among ASP and ASPX page?


No, it is not possible as both of these are running under different processes.

10. What are the caching techniques available? Page caching & Fragment Caching

ASP.NET Interview Questions set 8


1. What are the different types of authentication modes available?

1. Window.
2. Form.
3. Passport.
4. None.

2. Explain the steps involved to populate dataset with data?

Open connection
Initialize Adapter passing SQL and connection as parameter
Initialize Dataset
Call Fill method of the adapter passes dataset as the parameter
Close connection.

3. Can I have data from two different sources into a single dataset?

Yes, it is possible.

4. Is it possible load XML into a Data Reader?

No.

5. Is it possible to have tables in the dataset that are not bound to any data source?

Yes, we can create table object in code and add it to the dataset.

6. Why do you deploy an assembly into GAC?

To allow other application to access the shared assembly.

7. How do you uninstall assembly from GAC?

Use Gacutil.exe with U switch.

8. What does Regasm do?

The Assembly Registration tool reads the metadata within an assembly and adds the necessary entries to the registry, which allows COM clients
to create .NET Framework classes transparently. Once a class is registered, any COM client can use it as though the class were a COM class. The
class is registered only once, when the assembly is installed. Instances of classes within the assembly cannot be created from COM until they are
actually registered.

9. What is the difference between Execute Scalar and ExceuteNoneQuery?

Execute Scalar returns the value in the first row first column of a query result set.
ExceuteNonQuery return number of rows affected.
10. What is an assembly?

Assembly is a deployment unit of .NET application. In practical terms assembly is an Executable or a class library.

11. What is CLR?

The common language runtime is the execution engine for .NET Framework applications.
It provides a number of services, including the following:
• Code management (loading and execution)
Application memory isolation
• Verification of type safety
• Conversion of IL to native code
• Access to metadata (enhanced type information)
• Managing memory for managed objects
• Enforcement of code access security
• Exception handling, including cross-language exceptions
• Interoperation between managed code, COM objects, and pre-existing DLLs (unmanaged code and data)
• Automation of object layout
• Support for developer services (profiling, debugging, and so on)

12. What is the common type system (CTS)?

The common type system is a rich type system, built into the common language runtime that supports the types and operations found in most
programming languages. The common type system supports the complete implementation of a wide range of programming languages.

13. What is the Common Language Specification (CLS)?

The Common Language Specification is a set of constructs and constraints that serves as a guide for library writers and compiler writers. It
allows libraries to be fully usable from any language supporting the CLS, and for those languages to integrate with each other. The Common
Language Specification is a subset of the common type system. The Common Language Specification is also important to application developers
who are writing code that will be used by other developers. When developers design publicly accessible APIs following the rules of the CLS,
those APIs are easily used from all other programming languages that target the common language runtime.

14. What is the Microsoft Intermediate Language (MSIL)?

MSIL is the CPU-independent instruction set into which .NET Framework programs are compiled. It contains instructions for loading, storing,
initializing, and calling methods on objects.
Combined with metadata and the common type system, MSIL allows for true cross-language integration.
Prior to execution, MSIL is converted to machine code. It is not interpreted.

15. What is managed code and managed data?

ASP.NET Interview Questions set 14


1. How do you convert a string into an integer in .NET? Int32.Parse( string)

2. How do you box a primitive data type variable? Assign it to the object, pass an object.

3. Why do you need to box a primitive variable? To pass it by reference.

4. What’s the difference between Java and .NET garbage collectors?


Sun left the implementation of a specific garbage collector up to the JRE developer, so their performance
varies widely, depending on whose JRE you’re using. Microsoft standardized on their garbage collection.

5. How do you enforce garbage collection in .NET? System.GC.Collect ( );

6. Can you declare a C++ type destructor in C# like ~MyClass ()?


Yes, but what’s the point, since it will call Finalize(), and Finalize() has no guarantees when the memory will
be cleaned up, plus, it introduces additional load on the garbage collector.
7. What’s different about namespace declaration when comparing that to package declaration in Java?
No semicolon.

8. What’s the difference between const and read only?


You can initialize read only variables to some runtime values. Let’s say your program uses current date and
time as one of the values that won’t change. This way you declare public read only string DateT = new
DateTime ().ToString ().

9. What does \a character do? On most systems, produces a rather annoying beep.

10. Can you create enumerated data types in C#? Yes.

11. What’s different about switch statements in C#? No fall-throughs allowed.

12. What happens when you encounter a continue statement inside the for loop?
The code for the rest of the loop is ignored; the control is transferred back to the beginning of the loop.

13. Is goto statement supported in C#? How about Java?


Gotos are supported in C# to the fullest. In Java goto is a reserved keyword that provides absolutely no
functionality.

.NET interview questions(1-10)


What is .NET?

.NET is essentially a framework for software development. It is similar in nature to any other software development framework (J2EE etc) in that
it provides a set of runtime containers/capabilities, and a rich set of pre-built functionality in the form of class libraries and APIs The .NET
Framework is an environment for building, deploying, and running Web Services and other applications. It consists of three main parts: the
Common Language Runtime, the Framework classes, and ASP.NET.

How many languages .NET is supporting now?

When .NET was introduced it came with several languages. VB.NET, C#, COBOL and Perl, etc. The site DotNetLanguages.Net says 44
languages are supported.

How is .NET able to support multiple languages?

A language should comply with the Common Language Runtime standard to become a .NET language. In .NET, code is compiled to Microsoft
Intermediate Language (MSIL for short). This is called as Managed Code. This Managed code is run in .NET environment. So after compilation
to this IL the language is not a barrier. A code can call or use a function written in another language.

How ASP .NET different from ASP?

Scripting is separated from the HTML, Code is compiled as a DLL, these DLLs can be executed on the server.

What is view state?

The web is stateless. But in ASP.NET, the state of a page is maintained in the in the page itself automatically. How? The values are encrypted
and saved in hidden controls. this is done automatically by the ASP.NET. This can be switched off / on for a single control

How do you validate the controls in an ASP .NET page?

Using special validation controls that are meant for this. We have Range Validator, Email Validator.
Can the validation be done in the server side? Or this can be done only in the Client side?

Client side is done by default. Server side validation is also possible. We can switch off the client side and server side can be done.

How to manage pagination in a page?

Using pagination option in DataGrid control. We have to set the number of records for a page, then it takes care of pagination by itself.

What is ADO .NET and what is difference between ADO and ADO.NET?

ADO.NET is stateless mechanism. I can treat the ADO.Net as a separate in-memory database where in I can use relationships between the tables
and select insert and updates to the database. I can update the actual database as a batch.

Observations between VB.NET and VC#.NET?

Choosing a programming language depends on your language experience and the scope of the application you are building. While small
applications are often created using only one language, it is not uncommon to develop large applications using multiple languages.

For example, if you are extending an application with existing XML Web services, you might use a scripting language with little or no
programming effort. For client-server applications, you would probably choose the single language you are most comfortable with for the entire
application. For new enterprise applications, where large teams of developers create components and services for deployment across multiple
remote sites, the best choice might be to use several languages depending on developer skills and long-term maintenance expectations.

The .NET Platform programming languages – including Visual Basic .NET, Visual C#, and Visual C++ with managed extensions, and many
other programming languages from various vendors – use .NET Framework services and features through a common set of unified classes.
The .NET unified classes provide a consistent method of accessing the platform’s functionality. If you learn to use the class library, you will find
that all tasks follow the same uniform architecture. You no longer need to learn and master different API architectures to write your applications.

In most situations, you can effectively use all of the Microsoft programming languages. Nevertheless, each programming language has its relative
strengths and you will want to understand the features unique to each language. The following sections will help you choose the right
programming language for your application.

Visual Basic .NET Visual Basic .NET is the next generation of the Visual Basic language from Microsoft. With Visual Basic you can build .NET
applications, including Web services and ASP.NET Web applications, quickly and easily. Applications made with Visual Basic are built on the
services of the common language runtime and take advantage of the .NET Framework.

Visual Basic has many new and improved features such as inheritance, interfaces, and overloading that make it a powerful object-oriented
programming language. Other new language features include free threading and structured exception handling. Visual Basic fully integrates
the .NET Framework and the common language runtime, which together provide language interoperability, garbage collection, enhanced
security, and improved versioning support. A Visual Basic support single inheritance and creates Microsoft intermediate language (MSIL) as
input to native code compilers.

Visual Basic is comparatively easy to learn and use, and Visual Basic has become the programming language of choice for hundreds of thousands
of developers over the past decade. An understanding of Visual Basic can be leveraged in a variety of ways, such as writing macros in Visual
Studio and providing programmability in applications such as Microsoft Excel, Access, and Word.

Visual Basic provides prototypes of some common project types, including: Windows Application. Class Library. Windows Control Library.
ASP.NET Web Application. ASP.NET Web Service. Web Control Library. Console Application. Windows Service. Windows Service. Visual
C# .NET

Visual C# (pronounced C sharp) is designed to be a fast and easy way to create .NET applications, including Web services and ASP.NET Web
applications. Applications written in Visual C# are built on the services of the common language runtime and take full advantage of the .NET
Framework.

C# is a simple, elegant, type-safe, object-oriented language recently developed by Microsoft for building a wide range of applications. Anyone
familiar with C and similar languages will find few problems in adapting to C#. C# is designed to bring rapid development to the C++
programmer without sacrificing the power and control that are a hallmark of C and C++. Because of this heritage, C# has a high degree of fidelity
with C and C++, and developers familiar with these languages can quickly become productive in C#. C# provides intrinsic code trust
mechanisms for a high level of security, garbage collection, and type safety. C# supports single inheritance and creates Microsoft intermediate
language (MSIL) as input to native code compilers.
C# is fully integrated with the .NET Framework and the common language runtime, which together provide language interoperability, garbage
collection, enhanced security, and improved versioning support. C# simplifies and modernizes some of the more complex aspects of C and C++,
notably namespaces, classes, enumerations, overloading, and structured exception handling. C# also eliminates C and C++ features such as
macros, multiple inheritance, and virtual base classes. For current C++ developers, C# provides a powerful, high-productivity language
alternative.

Visual C# provides prototypes of some common project types, including: Windows Application. Class Library. Windows Control Library.
ASP.NET Web Application. ASP.NET Web Service. Web Control Library. Console Application. Windows Service.

.NET interview questions(11-20)


Advantages of migrating to VB.NET ?

Visual Basic .NET has many new and improved language features — such as inheritance, interfaces, and overloading that make it a powerful
object-oriented programming language. As a Visual Basic developer, you can now create multithreaded, scalable applications using explicit
multithreading. Other new language features in Visual Basic .NET include structured exception handling, custom attributes, and common
language specification (CLS) compliance.

The CLS is a set of rules that standardizes such things as data types and how objects are exposed and interoperate. Visual Basic .NET adds
several features that take advantage of the CLS. Any CLS-compliant language can use the classes, objects, and components you create in Visual
Basic .NET. And you, as a Visual Basic user, can access classes, components, and objects from other CLS-compliant programming languages
without worrying about language-specific differences such as data types.

CLS features used by Visual Basic .NET programs include assemblies, namespaces, and attributes.

These are the new features to be stated briefly: Inheritance Visual Basic .NET supports inheritance by allowing you to define classes that serve as
the basis for derived classes. Derived classes inherit and can extend the properties and methods of the base class. They can also override inherited
methods with new implementations. All classes created with Visual Basic .NET are inheritable by default. Because the forms you design are
really classes, you can use inheritance to define new forms based on existing ones.

Exception Handling Visual Basic .NET supports structured exception handling, using an enhanced version of the Try…Catch…Finally syntax
supported by other languages such as C++.

Structured exception handling combines a modern control structure (similar to Select Case or While) with exceptions, protected blocks of code,
and filters. Structured exception handling makes it easy to create and maintain programs with robust, comprehensive error handlers.

Overloading Overloading is the ability to define properties, methods, or procedures that have the same name but use different data types.
Overloaded procedures allow you to provide as many implementations as necessary to handle different kinds of data, while giving the appearance
of a single, versatile procedure. Overriding Properties and Methods The Overrides keyword allows derived objects to override characteristics
inherited from parent objects. Overridden members have the same arguments as the members inherited from the base class, but different
implementations. A member’s new implementation can call the original implementation in the parent class by preceding the member name with
MyBase.

Constructors and Destructors Constructors are procedures that control initialization of new instances of a class. Conversely, destructors are
methods that free system resources when a class leaves scope or is set to Nothing. Visual Basic .NET supports constructors and destructors using
the Sub New and Sub Finalize procedures.

Data Types Visual Basic .NET introduces three new data types. The Char data type is an unsigned 16-bit quantity used to store Unicode
characters. It is equivalent to the .NET Framework System. Char data type. The Short data type, a signed 16-bit integer, was named Integer in
earlier versions of Visual Basic. The Decimal data type is a 96-bit signed integer scaled by a variable power of 10. In earlier versions of Visual
Basic, it was available only within a Variant.

Interfaces Interfaces describe the properties and methods of classes, but unlike classes, do not provide implementations. The Interface statement
allows you to declare interfaces, while the Implements statement lets you write code that puts the items described in the interface into practice.

Delegates Delegates objects that can call the methods of objects on your behalf are sometimes described as type-safe, object-oriented function
pointers. You can use delegates to let procedures specify an event handler method that runs when an event occurs. You can also use delegates
with multithreaded applications. For details, see Delegates and the AddressOf Operator.

Shared Members Shared members are properties, procedures, and fields that are shared by all instances of a class. Shared data members are
useful when multiple objects need to use information that is common to all. Shared class methods can be used without first creating an object
from a class.
References References allow you to use objects defined in other assemblies. In Visual Basic .NET, references point to assemblies instead of type
libraries. For details, see References and the Imports Statement. Namespaces prevent naming conflicts by organizing classes, interfaces, and
methods into hierarchies.

Assemblies Assemblies replace and extend the capabilities of type libraries by, describing all the required files for a particular component or
application. An assembly can contain one or more namespaces.

Attributes Attributes enable you to provide additional information about program elements. For example, you can use an attribute to specify
which methods in a class should be exposed when the class is used as a XML Web service.

Multithreading Visual Basic .NET allows you to write applications that can perform multiple tasks independently. A task that has the potential of
holding up other tasks can execute on a separate thread, a process known as multithreading. By causing complicated tasks to run on threads that
are separate from your user interface, multithreading makes your applications more responsive to user input.

Using ActiveX Control in .Net ActiveX control is a special type of COM component that supports a User Interface. Using ActiveX Control in
your .Net Project is even easier than using COM component. They are bundled usually in .ocx files. Again a proxy assembly is made by .Net
utility AxImp.exe (which we will see shortly) which your application (or client) uses as if it is a .Net control or assembly.

Making Proxy Assembly For ActiveX Control: First, a proxy assembly is made using AxImp.exe (acronym for ActiveX Import) by writing
following command on Command Prompt:

C:> AxImp C:MyProjectsMyControl.ocx This command will make two dlls, e.g., in case of above command

MyControl.dll AxMyControl.dll The first file MyControl.dll is a .Net assembly proxy, which allows you to reference the ActiveX as if it were
non-graphical object.

The second file AxMyControl.dll is the Windows Control, which allows u to use the graphical aspects of activex control and use it in the
Windows Form Project.

Adding Reference of ActiveX Proxy Assembly in your Project Settings: To add a reference of ActiveX Proxy Assembly in our Project, do this:

o Select Project A Add Reference (Select Add Reference from Project Menu). o This will show you a dialog box, select .Net tab from the top of
window. o Click Browse button on the top right of window. o Select the dll file for your ActiveX Proxy Assembly (which is MyControl.dll) and
click OK o Your selected component is now shown in the ‘Selected Component’ List Box. Click OK again Some More On Using COM or
ActiveX in .Net

.Net only provides wrapper class or proxy assembly (Runtime Callable Wrapper or RCW) for COM or activeX control. In the background, it is
actually delegating the tasks to the original COM, so it does not convert your COM/activeX but just imports them.

A good thing about .Net is that when it imports a component, it also imports the components that are publically referenced by that component.
So, if your component, say MyDataAcsess.dll references ADODB.dll then .Net will automatically import that COM component too!

The Visual Studio.NET does surprise you in a great deal when u see that it is applying its intellisense (showing methods, classes, interfaces,
properties when placing dot) even on your imported COM components!!!! Isn’t it a magic or what?

When accessing thru RCW, .Net client has no knowledge that it is using COM component, it is presented just as another C# assembly.

U can also import COM component thru command prompt (for reference see Professional C# by Wrox)

U can also use your .Net components in COM, i.e., export your .net components (for reference see Professional C# by Wrox)

What is Machine.config?

Machine configuration file: The machine.config file contains settings that apply to the entire computer. This file is located in the %runtime install
path%Config directory. There is only one machine.config file on a computer. The Machine.Config file found in the “CONFIG” subfolder of your
.NET Framework install directory (c:WINNTMicrosoft.NETFramework{Version Number} CONFIG on Windows 2000 installations). The
machine.config, which can be found in the directory $WINDIR$Microsoft.NETFrameworkv1.0.3705CONFIG, is an XML-formatted
configuration file that specifies configuration options for the machine. This file contains, among many other XML elements, a browser Caps
element. Inside this element are a number of other elements that specify parse rules for the various User-Agents, and what properties each of
these parsing supports.
For example, to determine what platform is used, a filter element is used that specifies how to set the platform property based on what platform
name is found in the User-Agent string. Specifically, the machine.config file contains:

platform=Win95 platform=Win98 platform=WinNT …

That is, if in the User-Agent string the string “Windows 95″ or “Win95″ is found, the platform property is set to Win95. There are a number of
filter elements in the browserCaps element in the machine.config file that define the various properties for various User-Agent strings.

Hence, when using the Request.Browser property to determine a user’s browser features, the user’s agent string is matched up to particular
properties in the machine.config file. The ability for being able to detect a user’s browser’s capabilities, then, is based upon the honesty in the
browser’s sent User-Agent string. For example, Opera can be easily configured to send a User-Agent string that makes it appear as if it’s IE 5.5.
In this case from the Web server’s perspective (and, hence, from your ASP.NET Web page’s perspective), the user is visiting using IE 5.5, even
though, in actuality, he is using Opera.

What is Web.config?

In classic ASP all Web site related information was stored in the metadata of IIS. This had the disadvantage that remote Web developers couldn’t
easily make Web-site configuration changes. For example, if you want to add a custom 404 error page, a setting needs to be made through the IIS
admin tool, and you’re Web host will likely charge you a flat fee to do this for you. With ASP.NET, however, these settings are moved into an
XML-formatted text file (Web.config) that resides in the Web site’s root directory. Through Web.config you can specify settings like custom 404
error pages, authentication and authorization settings for the Web sitempilation options for the ASP.NET Web pages, if tracing should be
enabled, etc. The Web.config file is an XML-formatted file. At the root level is the tag. Inside this tag you can add a number of other tags, the
most common and useful one being the system.web tag, where you will specify most of the Web site configuration parameters. However, to
specify application-wide settings you use the tag.

For example, if we wanted to add a database connection string parameter we could have a Web.config file like so.

.NET interview questions(21-30)


What is the difference between ADO and ADO.NET?

ADO uses Recordsets and cursors to access and modify data. Because of its inherent design, Recordset can impact performance on the server side
by tying up valuable resources. In addition, COM marshalling – an expensive data conversion process – is needed to transmit a Recordset.
ADO.NET addresses three important needs that ADO doesn’t address:

1. Providing a comprehensive disconnected data-access model, which is crucial to the Web environment 2. Providing tight integration with XML,
and 3. Providing seamless integration with the .NET Framework (e.g., compatibility with the base class library’s type system). From an
ADO.NET implementation perspective, the Recordset object in ADO is eliminated in the .NET architecture. In its place, ADO.NET has several
dedicated objects led by the DataSet object and including the DataAdapter, and DataReader objects to perform specific tasks. In addition,
ADO.NET DataSets operate in disconnected state whereas the ADO RecordSet objects operated in a fully connected state.

In ADO, the in-memory representation of data is the RecordSet. In ADO.NET, it is the dataset. A RecordSet looks like a single table. If a
RecordSet is to contain data from multiple database tables, it must use a JOIN query, which assembles the data from the various database tables
into a single result table. In contrast, a dataset is a collection of one or more tables. The tables within a dataset are called data tables; specifically,
they are DataTable objects. If a dataset contains data from multiple database tables, it will typically contain multiple DataTable objects. That is,
each DataTable object typically corresponds to a single database table or view. In this way, a dataset can mimic the structure of the underlying
database.

In ADO you scan sequentially through the rows of the RecordSet using the ADO MoveNext method. In ADO.NET, rows are represented as
collections, so you can loop through a table as you would through any collection, or access particular rows via ordinal or primary key index. A
cursor is a database element that controls record navigation, the ability to update data, and the visibility of changes made to the database by other
users. ADO.NET does not have an inherent cursor object, but instead includes data classes that provide the functionality of a traditional cursor.
For example, the functionality of a forward-only, read-only cursor is available in the ADO.NET DataReader object.

There is one significant difference between disconnected processing in ADO and ADO.NET. In ADO you communicate with the database by
making calls to an OLE DB provider. In ADO.NET you communicate with the database through a data adapter (an OleDbDataAdapter,
SqlDataAdapter, OdbcDataAdapter, or OracleDataAdapter object), which makes calls to an OLE DB provider or the APIs provided by the
underlying data source.

What is the difference between VB and VB.NET?

Now VB.NET is object-oriented language. The following are some of the differences:
Data Type Changes

The .NET platform provides Common Type System to all the supported languages. This means that all the languages must support the same data
types as enforced by common language runtime. This eliminates data type incompatibilities between various languages. For example on the 32-
bit Windows platform, the integer data type takes 4 bytes in languages like C++ whereas in VB it takes 2 bytes. Following are the main changes
related to data types in VB.NET:

. Under .NET the integer data type in VB.NET is also 4 bytes in size. . VB.NET has no currency data type. Instead it provides decimal as a
replacement. . VB.NET introduces a new data type called Char. The char data type takes 2 bytes and can store Unicode characters. . VB.NET do
not have Variant data type. To achieve a result similar to variant type you can use Object data type. (Since every thing in .NET including
primitive data types is an object, a variable of object type can point to any data type). . In VB.NET there is no concept of fixed length strings. . In
VB6 we used the Type keyword to declare our user-defined structures. VB.NET introduces the structure keyword for the same purpose.
Declaring Variables Consider this simple example in VB6: Dim x,y as integer

In this example VB6 will consider x as variant and y as integer, which is somewhat odd behavior. VB.NET corrects this problem, creating both x
and y as integers.

Furthermore, VB.NET allows you to assign initial values to the variables in the declaration statement itself: br> Dim str1 as string = Hello

VB.NET also introduces Read-Only variables. Unlike constants Read-Only variables can be declared without initialization but once you assign a
value to it, it cannot be changes.

Initialization here Dim readonly x as integer In later code X=100 Now x can’t be changed X=200 *********** Error ********** Property
Syntax In VB.NET, we anymore don’t have separate declarations for Get and Set/Let. Now, everything is done in a single property declaration.
This can be better explained by the following example. Public [ReadOnly | WriteOnly] Property PropertyName as Datatype Get Return m_var
End Get Set M_var = value End Set End Property Example: Private _message as String Public Property Message As String Get Return _message
End Get Set _message = Value End Set End Property

ByVal is the default – This is a crucial difference betwen VB 6.0 and VB.NET, where the default in VB 6.0 was by reference. But objects are still
passed by reference.

Invoking Subroutines In previous versions of VB, only functions required the use of parentheses around the parameter list. But in VB.NET all
function or subroutine calls require parentheses around the parameter list. This also applies, even though the parameter list is empty.

User-Defined Types – VB.NET does away with the keyword Type and replaces it with the keyword Structure Public Structure Student Dim
strName as String Dim strAge as Short End Structure Procedures and Functions

In VB6 all the procedure parameters are passed by reference (ByRef) by default. In VB.NET they are passed by value (ByVal) by default.
Parantheses are required for calling procedures and functions whether they accept any parameters or not. In VB6 functions returned values using
syntax like: FuntionName = return_value. In VB.NET you can use the Return keyword (Return return_value) to return values or you can
continue to use the older syntax, which is still valid.

Scoping VB.NET now supports block-level scoping of variables. If your programs declare all of the variables at the beginning of the function or
subroutine, this will not be a problem. However, the following VB 6.0 will cause an issue while upgrading to VB .NET

Do While objRs.Eof Dim J as Integer J=0 If objRs(“flag”)=”Y” then J=1 End If objRs.MoveNext Wend If J Then Msgbox “Flag is Y” End If

In the above example the variable J will become out of scope just after the loop, since J was declared inside the While loop.

Exception Handling

The most wanted feature in earlier versions of VB was its error handling mechanism. The older versions relied on error handlers such as “On
Error GoTo and On Error Resume Next. VB.NET provides us with a more stuructured approach. The new block structure allows us to track the
exact error at the right time. The new error handling mechanism is refered to as Try…Throw…Catch…Finally. The following example will
explain this new feature.

Sub myOpenFile() Try Open “myFile” For Output As #1 Write #1, myOutput Catch Kill “myFile” Finally Close #1 End try End Sub

The keyword SET is gone – Since everything in VB.NET is an object. So the keyword SET is not at all used to differentiate between a simple
variable assignment and an object assignment. So, if you have the following statement in VB 6.0
Set ObjConn = Nothing Should be replaced as ObjConn = Nothing. Constructor and Destructor

The constructor procedure is one of the many new object-oriented features of VB.NET. The constructor in VB.NET replaces the Class_Initialize
in VB 6.0. All occurance of Class_Initialize in previous versions of VB should now be placed in a class constructor. In VB.NET, a constructor is
added to a class by adding a procedure called New. We can also create a class destructor, which is equivalent to Class_Terminate event in VB
6.0, by adding a sub-procedure called Finalize to our class. Usage of Return In VB.NET, we can use the keyword return to return a value from
any function. In previous versions, we used to assign the value back with the help of the function name itself. The following example explains
this:

Public Function Sum (intNum1 as Integer, intNum2 as Integer) as Integer Dim intSum as Integer intSum = intNum1 + intNum2 Return intSum
End Function Static Methods

VB.NET now allows you to create static methods in your classes. Static methods are methods that can be called without requiring the developer
to create instance of the class. For example, if you had a class named Foo with the non-static method NonStatic() and the static method Static(),
you could call the Static() method like so:

Foo.Static()

However, non-static methods require than an instance of the class be created, like so:

Create an instance of the Foo class Dim objFoo as New Foo() Execute the NonStatic() method ObjFoo.NonStatic()

To create a static method in a VB.NET, simply prefix the method definition with the keyword Shared.

What is a Strong Name?

A strong name consists of the assembly’s identity its simple text name, version number, and culture information (if provided) plus a public key
and a digital signature. It is generated from an assembly file (the file that contains the assembly manifest, which in turn contains the names and
hashes of all the files that make up the assembly), using the corresponding private key. Assemblies with the same strong name are expected to be
identical.

Strong names guarantee name uniqueness by relying on unique key pairs. No one can generate the same assembly name that you can, because an
assembly generated with one private key has a different name than an assembly generated with another private key.

When you reference a strong-named assembly, you expect to get certain benefits, such as versioning and naming protection. If the strong-named
assembly then references an assembly with a simple name, which does not have these benefits, you lose the benefits you would derive from using
a strong-named assembly and revert to DLL conflicts. Therefore, strong-named assemblies can only reference other strong-named assemblies.

There are two ways to sign an assembly with a strong name:

1. Using the Assembly Linker (Al.exe) provided by the .NET Framework SDK. 2. Using assembly attributes to insert the strong name
information in your code. You can use either the AssemblyKeyFileAttribute or the AssemblyKeyNameAttribute, depending on where the key file
to be used is located.

To create and sign an assembly with a strong name using the Assembly Linker, at the command prompt, type the following command: al /out:
/keyfile:

In this command, assembly name is the name of the assembly to sign with a strong name, module name is the name of the code module used to
create the assembly, and file name is the name of the container or file that contains the key pair.

The following example signs the assembly MyAssembly.dll with a strong name using the key file sgKey.snk.

al /out:MyAssembly.dll MyModule.netmodule /keyfile:sgKey.snk

To sign an assembly with a strong name using attributes

In a code module, add the AssemblyKeyFileAttribute or the AssemblyKeyNameAttribute, specifying the name of the file or container that
contains the key pair to use when signing the assembly with a strong name. The following code example uses the AssemblyKeyFileAttribute with
a key file called sgKey.snk.

[Visual Basic] [C#] [ assembly:AssemblyKeyFileAttribute(@"....sgKey.snk")]


What is a Manifest?

An assembly manifest contains all the metadata needed to specify the assembly’s version requirements and security identity, and all metadata
needed to define the scope of the assembly and resolve references to resources and classes. The assembly manifest can be stored in either a PE
(Portable Executable) file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a standalone PE (Portable Executable) file
that contains only assembly manifest information. The following table shows the information contained in the assembly manifest. The first four
items the assembly name, version number, culture, and strong name information make up the assembly’s identity.

Assembly name: A text string specifying the assembly’s name.

Version number: A major and minor version number, and a revision and build number. The common language runtime uses these numbers to
enforce version policy.

Culture: Information on the culture or language the assembly supports. This information should be used only to designate an assembly as a
satellite assembly containing culture- or language-specific information. (An assembly with culture information is automatically assumed to be a
satellite assembly.) Strong name information: The public key from the publisher if the assembly has been given a strong name. List of all files in
the assembly:

A hash of each file contained in the assembly and a file name. Note that all files that make up the assembly must be in the same directory as the
file containing the assembly manifest.

Type reference information: Information used by the runtime to map a type reference to the file that contains its declaration and implementation.
This is used for types that are exported from the assembly.

Information on referenced assemblies: A list of other assemblies that are statically referenced by the assembly. Each reference includes the
dependent assembly’s name, assembly metadata (version, culture, operating system, and so on), and public key, if the assembly is strong named.

Creating a Key Pair?

You can create a key pair using the Strong Name tool (Sn.exe). Key pair files usually have an .snk extension. To create a key pair At the
command prompt, type the following command:

sn k

In this command, file name is the name of the output file containing the key pair. The following example creates a key pair called sgKey.snk.

sn -k sgKey.snk

What is the difference between “using System.Data;” and directly adding the reference from “Add References Dialog Box”?

When u compile a program using command line, u add the references using /r switch. When you compile a program using Visual Studio, it adds
those references to our assembly, which are added using “Add Reference” dialog box. While “using” statement facilitates us to use classes
without using their fully qualified names.

For example: if u have added a reference to “System.Data.SqlClient” using “Add Reference” dialog box then u can use SqlConnection class like
this:

System.Data.SqlClient.SqlConnection

But if u add a “using System.Data.SqlClient” statement at the start of ur code then u can directly use SqlConnection class. On the other hand if u
add a reference using “using System.Data.SqlClient” statement, but don’t add it using “Add Reference” dialog box, Visual Studio will give error
message while we compile the program.

What is GAC?

The global assembly cache stores assemblies specifically designated to be shared by several applications on the computer. You should share
assemblies by installing them into the global assembly cache only when you need to. Assemblies deployed in the global assembly cache must
have a strong name. When an assembly is added to the global assembly cache, integrity checks are performed on all files that make up the
assembly. The cache performs these integrity checks to ensure that an assembly has not been tampered with, for example, when a file has
changed but the manifest does not reflect the change. Use a developer tool called the Global Assembly Cache tool (Gacutil.exe), provided by
the .NET Framework SDK or Use Windows Explorer to drag assemblies into the cache. To install a strong-named assembly into the global
assembly cache At the command prompt, type the following command:

gacutil I

In this command, assembly name is the name of the assembly to install in the global assembly cache.

What is a Metadata?

Metadata is information about a PE. In COM, metadata is communicated through non-standardized type libraries.

In .NET, this data is contained in the header portion of a COFF-compliant PE and follows certain guidelines; it contains information such as the
assembly’s name, version, language (spoken, not computera.k.a., culture), what external types are referenced, what internal types are exposed,
methods, properties, classes, and much more.

The CLR uses metadata for a number of specific purposes. Security is managed through a public key in the PE’s header.

Information about classes, modules, and so forth allows the CLR to know in advance what structures are necessary. The class loader component
of the CLR uses metadata to locate specific classes within assemblies, either locally or across networks.

Just-in-time (JIT) compilers use the metadata to turn IL into executable code.

Other programs take advantage of metadata as well.

A common example is placing a Microsoft Word document on a Windows 2000 desktop. If the document file has completed comments, author,
title, or other Properties metadata, the text is displayed as a tool tip when a user hovers the mouse over the document on the desktop. You can use
the Ildasm.exe utility to view the metadata in a PE. Literally, this tool is an IL disassembler.

What is managed code and managed data?

Managed code is code that is written to target the services of the Common Language Runtime. In order to target these services, the code must
provide a minimum level of information (metadata) to the runtime. All C#, Visual Basic .NET, and JScript .NET code is managed by default.
Visual Studio .NET C++ code is not managed by default, but the compiler can produce managed code by specifying a command-line switch
(/CLR). Closely related to managed code is managed data–data that is allocated and de- allocated by the Common Language Runtime’s garbage
collector. C#, Visual Basic, and JScript .NET data is managed by default. C# data can, however, be marked as unmanaged through the use of
special keywords. Visual Studio .NET C++ data is unmanaged by default (even when using the /CLR switch), but when using Managed
Extensions for C++, a class can be marked as managed using the __gc keyword. As the name suggests, this means that the memory for instances
of the class is managed by the garbage collector. In addition, the class becomes a full participating member of the .NET Framework community,
with the benefits and restrictions that it brings. An example of a benefit is proper interoperability with classes written in other languages (for
example, a managed C++ class can inherit from a Visual Basic class). An example of a restriction is that a managed class can only inherit from
one base class.

What is .NET / .NET Framework?

It is a Framework in which Windows applications may be developed and run. The Microsoft .NET Framework is a platform for building,
deploying, and running Web Services and applications. It provides a highly productive, standards-based, multi-language environment for
integrating existing investments with next-generation applications and services as well as the agility to solve the challenges of deployment and
operation of Internet-scale applications. The .NET Framework consists of three main parts: the common language runtime, a hierarchical set of
unified class libraries, and a componentized version of Active Server Pages called ASP.NET. The .NET Framework provides a new
programming model and rich set of classes designed to simplify application development for Windows, the Web, and mobile devices. It provides
full support for XML Web services, contains robust security features, and delivers new levels of programming power. The .NET Framework is
used by all Microsoft languages including Visual C#, Visual J#, and Visual C++.

What is Reflection?

It extends the benefits of metadata by allowing developers to inspect and use it at runtime. For example, dynamically determine all the classes
contained in a given assembly and invoke their methods. Reflection provides objects that encapsulate assemblies, modules, and types. You can
use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object. You can then
invoke the type’s methods or access its fields and properties. Namespace: System.Reflection

What is “Common Type System” (CTS)?


CTS defines all of the basic types that can be used in the .NET Framework and the operations performed on those type. All this time we have
been talking about language interoperability, and .NET Class Framework. None of this is possible without all the language sharing the same data
types. What this means is that an int should mean the same in VB, VC++, C# and all other .NET compliant languages. This is achieved through
introduction of Common Type System (CTS).

.NET interview questions(31-40)


What is “Common Language Specification” (CLS)?

CLS is the collection of the rules and constraints that every language (that seeks to achieve .NET compatibility) must follow. It is a subsection of
CTS and it specifies how it shares and extends one another libraries.

What is “Common Language Runtime” (CLR)?

CLR is .NET equivalent of Java Virtual Machine (JVM). It is the runtime that converts a MSIL code into the host machine language code, which
is then executed appropriately. The CLR is the execution engine for .NET Framework applications. It provides a number of services, including:

- Code management (loading and execution) - Application memory isolation - Verification of type safety - Conversion of IL to native code. -
Access to metadata (enhanced type information) - Managing memory for managed objects - Enforcement of code access security - Exception
handling, including cross-language exceptions - Interoperation between managed code, COM objects, and pre-existing DLL’s (unmanaged code
and data) - Automation of object layout - Support for developer services (profiling, debugging, and so on).

What are Attributes?

Attributes are declarative tags in code that insert additional metadata into an assembly. There exist two types of attributes in the .NET
Framework: Predefined attributes such as AssemblyVersion, which already exist and are accessed through the Runtime Classes; and custom
attributes, which you write yourself by extending the System.Attribute class.

What are the Types of Assemblies?

Assemblies are of two types: 1. Private Assemblies 2. Shared Assemblies Private Assemblies: The assembly is intended only for one application.
The files of that assembly must be placed in the same folder as the application or in a sub folder. No other application will be able to make a call
to this assembly. The advantage of having a private assembly is that, it makes naming the assembly very easy, since the developer need not worry
about name clashes with other assemblies. As long as the assembly has a unique name within the concerned application, there won’t be any
problems. Shared Assemblies: If the assembly is to be made into a Shared Assembly, then the naming conventions are very strict since it has to
be unique across the entire system. The naming conventions should also take care of newer versions of the component being shipped. These are
accomplished by giving the assembly a Shared Name. Then the assembly is placed in the global assembly cache, which is a folder in the file
system reserved for shared assemblies.

What is an Intermediate language?

Assemblies are made up of IL code modules and the metadata that describes them. Although programs may be compiled via an IDE or the
command line, in fact, they are simply translated into IL, not machine code. The actual machine code is not generated until the function that
requires it is called. This is the just-in-time, or JIT, compilation feature of .NET. JIT compilation happens at runtime for a variety of reasons, one
of the most ambitious being Microsoft’s desire for cross-platform .NET adoption. If a CLR is built for another operating system (UNIX or Mac),
the same assemblies will run in addition to the Microsoft platforms. The hope is that .NET assemblies are write-once-run-anywhere applications.
This is a .NET feature that works behind-the-scenes, ensuring that developers are not limited to writing applications for one single line of
products. No one has demonstrated whether or not this promise will ever truly materialize.

CTS/CLS

The MSIL Instruction Set Specification is included with the .NET SDK, along with the IL Assembly Language Programmers Reference. If a
developer wants to write custom .NET programming languages, these are the necessary specifications and syntax. The CTS and CLS define the
types and syntaxes that every .NET language needs to embrace. An application may not expose these features, but it must consider them when
communicating through IL.

ASP.NET Authentication Providers and IIS Security

ASP.NET implements authentication using authentication providers, which are code modules that verify credentials and implement other security
functionality such as cookie generation. ASP.NET supports the following three authentication providers:
Forms Authentication: Using this provider causes unauthenticated requests to be redirected to a specified HTML form using client side
redirection. The user can then supply logon credentials, and post the form back to the server. If the application authenticates the request (using
application-specific logic), ASP.NET issues a cookie that contains the credentials or a key for reacquiring the client identity. Subsequent requests
are issued with the cookie in the request headers, which means that subsequent authentications are unnecessary.

Passport Authentication: This is a centralized authentication service provided by Microsoft that offers a single logon facility and membership
services for participating sites. ASP.NET, in conjunction with the Microsoft® Passport software development kit (SDK), provides similar
functionality as Forms Authentication to Passport users.

Windows Authentication: This provider utilizes the authentication capabilities of IIS. After IIS completes its authentication, ASP.NET uses the
authenticated identity’s token to authorize access.

To enable a specified authentication provider for an ASP.NET application, you must create an entry in the application’s configuration file as
follows: // web.config file

What is the difference between ASP and ASP.NET?

ASP is interpreted. ASP.NET Compiled event base programming. Control events for text button can be handled at client javascript only. Since
we have server controls events can handle at server side. More error handling.

ASP .NET has better language support, a large set of new controls and XML based components, and better user authentication.

ASP .NET provides increased performance by running compiled code.

ASP .NET code is not fully backward compatible with ASP.

ASP .NET also contains a new set of object oriented input controls, like programmable list boxes, validation controls. A new data grid control
supports sorting, data paging, and everything you expect from a dataset control. The first request for an ASP.NET page on the server will compile
the ASP .NET code and keep a cached copy in memory. The result of this is greatly increased performance.

ASP .NET is not fully compatible with earlier versions of ASP, so most of the old ASP code will need some changes to run under ASP .NET. To
overcome this problem,

ASP .NET uses a new file extension “.aspx”. This will make ASP .NET applications able to run side by side with standard ASP applications on
the same server. Using COM Component in .Net ?

As most of you know that .Net does not encourage the development of COM components and provides a different solution to making reusable
components through Assemblies. But, there are a lot of COM components present which our .Net application might need to use. Fortunately, .Net
provides an extremely simple approach to achieve this. This is achieved by using ‘Wrapper Classes’ and ‘Proxy Components’. .Net wraps
the COM component into .Net assembly technically called ‘Runtime Callable Wrapper’ or RCW. Then u can call and use your COM
component just as a .Net (or C#, if u are using C#) Assembly.

What is an assembly?

An assembly is the primary building block of a .NET Framework application. It is a collection of functionality that is built, versioned, and
deployed as a single implementation unit (as one or more files). All managed types and resources are marked either as accessible only within
their implementation unit, or as accessible by code outside that unit. .NET Assembly contains all the metadata about the modules, types, and
other elements it contains in the form of a manifest. The CLR loves assemblies because differing programming languages are just perfect for
creating certain kinds of applications. For example, COBOL stands for Common Business-Oriented Language because it’s tailor-made for
creating business apps. However, it’s not much good for creating drafting programs. Regardless of what language you used to create your
modules, they can all work together within one Portable Executable Assembly. There’s a hierarchy to the structure of .NET code. That hierarchy
is Assembly – > Module -> Type -> Method.” Assemblies can be static or dynamic. Static assemblies can include .NET Framework types
(interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files, and so on). Static assemblies are stored on disk
in portable executable (PE) files. You can also use the .NET Framework to create dynamic assemblies, which are run directly from memory and
are not saved to disk before execution. You can save dynamic assemblies to disk after they have executed.

What is a Web Service?

A web service is a software component that exposes itself through the open communication channels of the Internet. Applications running on
remote machines, on potentially different platforms, can access these components in a language and platform-independent manner. A Web
Service is a group of functions, packaged together for use in a common framework throughout a network.
webFarm Vs webGardens

A web farm is a multi-server scenario. So we may have a server in each state of US. If the load on one server is in excess then the other servers
step in to bear the brunt. How they bear it is based on various models. 1. RoundRobin. (All servers share load equally) 2. NLB (economical) 3.
HLB (expensive but can scale up to 8192 servers) 4. Hybrid (of 2 and 3). 5. CLB (Component load balancer). A web garden is a multi-processor
setup. i.e., a single server (not like the multi server above). How to implement webfarms in .Net: Go to web.config and Here for mode = you have
4 options. a) Say mode=inproc (non web farm but fast when you have very few customers). b) Say mode=StateServer (for webfarm) c) Say
mode=SqlServer (for webfarm) Whether to use option b or c depends on situation. StateServer is faster but SqlServer is more reliable and used
for mission critical applications. How to use webgardens in .Net: Go to web.config and Change the false to true. You have one more attribute that
is related to webgarden in the same tag called cpuMask.

.NET interview questions(41-50)


What is the difference between a namespace and assembly name?

A namespace is a logical naming scheme for types in which a simple type name, such as MyType, is preceded with a dot-separated hierarchical
name. Such a naming scheme is completely under control of the developer. For example, types MyCompany.FileAccess.A and
MyCompany.FileAccess.B might be logically expected to have functionally related to file access. The .NET Framework uses a hierarchical
naming scheme for grouping types into logical categories of related functionality, such as the ASP.NET application framework, or remoting
functionality. Design tools can make use of namespaces to make it easier for developers to browse and reference types in their code. The concept
of a namespace is not related to that of an assembly. A single assembly may contain types whose hierarchical names have different namespace
roots, and a logical namespace root may span multiple assemblies. In the .NET Framework, a namespace is a logical design-time naming
convenience, whereas an assembly establishes the name scope for types at run time.

What’s a Windows process?

It’s an application that’s running and had been allocated memory.

What’s typical about a Windows process in regards to memory allocation?

Each process is allocated its own block of available RAM space, no process can access another process’ code or data. If the process crashes, it
dies alone without taking the entire OS or a bunch of other applications down.

Explain what relationship is between a Process, Application Domain, and Application?

Each process is allocated its own block of available RAM space, no process can access another process’ code or data. If the process crashes, it
dies alone without taking the entire OS or a bunch of other applications down. A process is an instance of a running application. An application is
an executable on the hard drive or network. There can be numerous processes launched of the same application (5 copies of Word running), but 1
process can run just 1 application.

What are possible implementations of distributed applications in .NET?

.NET Remoting and ASP.NET Web Services. If we talk about the Framework Class Library, noteworthy classes are in
System.Runtime.Remoting and System.Web.Services.

What are the consideration in deciding to use .NET Remoting or ASP.NET Web Services?

Remoting is a more efficient communication exchange when you can control both ends of the application involved in the communication process.
Web Services provide an open-protocol-based exchange of information. Web Services are best when you need to communicate with an external
organization or another (non-.NET) technology.

What’s a proxy of the server object in .NET Remoting?

It’s a fake copy of the server object that resides on the client side and behaves as if it was the server. It handles the communication between real
server object and the client object. This process is also known as marshaling.

What are remotable objects in .NET Remoting?

Remotable objects are the objects that can be marshaled across the application domains. You can marshal by value, where a deep copy of the
object is created and then passed to the receiver. You can also marshal by reference, where just a reference to an existing object is passed. What
are channels in .NET Remoting?
Channels represent the objects that transfer the other serialized objects from one application domain to another and from one computer to
another, as well as one process to another on the same box. A channel must exist before an object can be transferred.

.NET interview questions(51-60)


What security measures exist for .NET Remoting in System.Runtime.Remoting?

None. Security should be taken care of at the application level. Cryptography and other security techniques can be applied at application or server
level.

What is a formatter?

A formatter is an object that is responsible for encoding and serializing data into messages on one end, and deserializing and decoding messages
into data on the other end.

Choosing between HTTP and TCP for protocols and Binary and SOAP for formatters, what are the trade-offs?

Binary over TCP is the most effiecient, SOAP over HTTP is the most interoperable.

What’s SingleCall activation mode used for?

If the server object is instantiated for responding to just one single request, the request should be made in SingleCall mode.

What’s Singleton activation mode?

A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is determined by lifetime lease.

How do you define the lease of the object?

By implementing ILease interface when writing the class code.

Can you configure a .NET Remoting object via XML file?

Yes, via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings take precedence over
machine.config.

How can you automatically generate interface for the remotable object in .NET with Microsoft tools?

Use the Soapsuds tool.

What is Delegation?

A delegate acts like a strongly type function pointer. Delegates can invoke the methods that they reference without making explicit calls to those
methods. Delegate is an entity that is entrusted with the task of representation, assign or passing on information. In code sense, it means a
Delegate is entrusted with a Method to report information back to it when a certain task (which the Method expects) is accomplished outside the
Method’s class. What is “Microsoft Intermediate Language” (MSIL)?

A .NET programming language (C#, VB.NET, J# etc.) does not compile into executable code; instead it compiles into an intermediate code
called Microsoft Intermediate Language (MSIL). As a programmer one need not worry about the syntax of MSIL – since our source code in
automatically converted to MSIL. The MSIL code is then send to the CLR (Common Language Runtime) that converts the code to machine
language, which is, then run on the host machine. MSIL is similar to Java Byte code. MSIL is the CPU-independent instruction set into which
.NET Framework programs are compiled. It contains instructions for loading, storing, initializing, and calling methods on objects. Combined
with metadata and the common type system, MSIL allows for true cross- language integration Prior to execution, MSIL is converted to machine
code. It is not interpreted.

.NET interview questions(61-70)


Differences between Datagrid, Datalist and Repeater?
1. Datagrid has paging while Datalist doesnt. 2. Datalist has a property called repeat. Direction = vertical/horizontal. (This is of great help in
designing layouts). This is not there in Datagrid. 3. A repeater is used when more intimate control over html generation is required. 4. When only
checkboxes/radiobuttons are repeatedly served then a checkboxlist or radiobuttonlist are used as they involve fewer overheads than a Datagrid.
The Repeater repeats a chunk of HTML you write, it has the least functionality of the three. DataList is the next step up from a Repeater; accept
you have very little control over the HTML that the control renders. DataList is the first of the three controls that allow you Repeat-Columns
horizontally or vertically. Finally, the DataGrid is the motherload. However, instead of working on a row-by-row basis, you’re working on a
column-by-column basis. DataGrid caters to sorting and has basic paging for your disposal. Again you have little contro, over the HTML. NOTE:
DataList and DataGrid both render as HTML tables by default. Out of the 3 controls, I use the Repeater the most due to its flexibility w/ HTML.
Creating a Pagination scheme isn’t that hard, so I rarely if ever use a DataGrid. Occasionally I like using a DataList because it allows me to easily
list out my records in rows of three for instance.

I am constantly writing the drawing procedures with System.Drawing.Graphics, but having to use the try and dispose blocks is too time-
consuming with Graphics objects. Can I automate this?

Yes, the code

System.Drawing.Graphics canvas = new System.Drawing.Graphics(); try { //some code } finally canvas.Dispose(); is functionally equivalent to
using (System.Drawing.Graphics canvas = new System.Drawing.Graphics()) { //some code } //canvas.Dispose() gets called automatically

How do you trigger the Paint event in System.Drawing?

Invalidate the current form, the OS will take care of repainting. The Update method forces the repaint.

With these events, why wouldn’t Microsoft combine Invalidate and Paint, so that you wouldn’t have to tell it to repaint, and then to force it to
repaint?

Painting is the slowest thing the OS does, so usually telling it to repaint, but not forcing it allows for the process to take place in the background.

How can you assign an RGB color to a System.Drawing.Color object?

Call the static method FromArgb of this class and pass it the RGB values.

What class does Icon derive from? Isn’t it just a Bitmap with a wrapper name around it?

No, Icon lives in System.Drawing namespace. It’s not a Bitmap by default, and is treated separately by .NET. However, you can use ToBitmap
method to get a valid Bitmap object from a valid Icon object.

Before in my VB app I would just load the icons from DLL. How can I load the icons provided by .NET dynamically?

By using System.Drawing.SystemIcons class, for example System.Drawing.SystemIcons.Warning produces an Icon with a warning sign in it.
When displaying fonts, what’s the difference between pixels, points and ems?

A pixel is the lowest-resolution dot the computer monitor supports. Its size depends on user’s settings and monitor size. A point is always 1/72 of
an inch. An em is the number of pixels that it takes to display the letter M. What is the difference between VB 6 and VB.NET?

Answer1 VB

1,Object-based Language 2,Doesnot support Threading 3,Not powerful Exception handling mechanism 4,Doesnot having support for the console
based applications 5,Cannot use more than one version of com objects in vb application called DLL error 6,Doesnot support for the Disconnected
data source.

VB.Net

1,Object-oriented Language 2,supports Threading 3,powerful Exception handling mechanism 4,having support for the console based applications
5,More than one version of dll is supported 6,supports the Disconnected data source by using Dataset class

Answer2 VB: 1. Object-based language 2. Does not support inheritance 3. ADO.Net does not give support for disconnected data architecture 4.
No interoperability function 5. No support for threading

VB.Net 1. Object-Oriented Programming lanugage 2. ADO.Net gives support for disconnected data architecture 3. It provides interoperability 4.
It uses managed code 5. supports threading 6. provides access to third-party controls like COM, DCOM
Answer2 1.The concept of the complete flow of execution of a program from start to finish: Visual Basic hides this aspect of programs from you,
so that the only elements of a Visual Basic program you code are the event handlers and any methods in class modules. C# makes the complete
program available to you as source code. The reason for this has to do with the fact that C# can be seen, philosophically, as next-generation C++.
The roots of C++ go back to the 1960s and predate windowed user interfaces and sophisticated operating systems. C++ evolved as a low-level,
closeto- the-machine, all-purpose language. To write GUI applications with C++ meant that you had to invoke the system calls to create and
interact with the windowed forms. C# has been designed to build on this tradition while simplifying and modernizing C++, to combine the low-
level performance benefits of C++ with the ease of coding in Visual Basic. Visual Basic, on the other hand, is designed specifically for rapid
application development of Windows GUI applications. For this reason, in Visual Basic all the GUI boilerplate code is hidden, and all the Visual
Basic programmer implements are the event handlers. In C# on the other hand, this boilerplate code is exposed as part of your source code. 2.
Classes and inheritance: C# is a genuine object-oriented language, unlike Visual Basic, requiring all code to be a part of a class. It also includes
extensive support for implementation inheritance. Indeed, most well-designed C# programs will be very much designed around this form of
inheritance, which is completely absent in Visual Basic.

What are the authentication methods in .NET?

There are 4 types of authentications. 1.WINDOWS AUTHENTICATION 2.FORMS AUTHENTICATION 3.PASSPORT AUTHENTICATION
4.NONE/CUSTOM AUTHENTICATION

The authentication option for the ASP.NET application is specified by using the tag in the Web.config file, as shown below: other authentication
options 1. WINDOWS AUTHENTICATION Schemes I. Integrated Windows authentication II. Basic and basic with SSL authentication III.
Digest authentication IV. Client Certificate authentication

2. FORMS AUTHENTICATION You, as a Web application developer, are supposed to develop the Web page and authenticate the user by
checking the provided user ID and password against some user database

3.PASSPORT AUTHENTICATION A centralized service provided by Microsoft, offers a single logon point for clients. Unauthenticated users
are redirected to the Passport site

4 NONE/CUSTOM AUTHENTICATION: If we don’t want ASP.NET to perform any authentication, we can set the authentication mode to
“none”. The reason behind this decision could be: We don’t want to authenticate our users, and our Web site is open for all to use. We want
to provide our own custom authentication

What is Serialization in .NET?

Anwer1 The serialization is the process of converting the objects into stream of bytes. they or used for transport the objects(via remoting) and
persist objects(via files and databases)

Answer2 When developing smaller applications that do not have a database (or other formal storage mechanism) or data that doesn’t need to be
stored in a database (such as the state of a web application), you often still would like to save the data for later retrieval. There are many ways to
do this, but many of them are subject to a lot of extra code (work) and extra time spent debugging. With .NET, there is now an easy way to add
this functionality to your code with only a few lines of easily tested code. This easy way is called serialization.

Serialization is the process of storing an object, including all of its public and private fields, to a stream. Deserialization is the opposite –
restoring an object’s field values from a stream. The stream is generally in the form of a FileStream, but does not have to be. It could be a
memory stream or any other object that is of type IO.Stream. The format can be anything from XML to binary to SOAP

.NET interview questions(71-80)


What is Serialization in .NET?

Anwer1 The serialization is the process of converting the objects into stream of bytes. they or used for transport the objects(via remoting) and
persist objects(via files and databases)

Answer2 When developing smaller applications that do not have a database (or other formal storage mechanism) or data that doesn’t need to be
stored in a database (such as the state of a web application), you often still would like to save the data for later retrieval. There are many ways to
do this, but many of them are subject to a lot of extra code (work) and extra time spent debugging. With .NET, there is now an easy way to add
this functionality to your code with only a few lines of easily tested code. This easy way is called serialization.

Serialization is the process of storing an object, including all of its public and private fields, to a stream. Deserialization is the opposite –
restoring an object’s field values from a stream. The stream is generally in the form of a FileStream, but does not have to be. It could be a
memory stream or any other object that is of type IO.Stream. The format can be anything from XML to binary to SOAP.
What’s the use of System.Diagnostics.Process class?

By using System.Diagnostics.Process class, we can provide access to the files which are presented in the local and remote system. Example:
System.Diagnostics.Process(”c:\mlaks\example.txt”) — local file System.Diagnostics.Process(”http://www.mlaks.com\example.txt”)
— remote file

What are the authentication methods in .NET?

Abstract class: This class has abstract methods (no body). This class cannot be instantiated. One needs to provide the implementation of the
methods by overriding them in the derived class. No Multiple Inheritance. Interfaces: Interface class contains all abstract methods which are
public by default. All of these methods must be implemented in the derived class. One can inherit from from more than one interface thus
provides for Multiple Inheritance.

re-clarification of object based:

VB6 DOES support polymorphism and interface inheritance. It also supports the “Implements” keyword. What is not supported in vb6 is
implementation inheritance. Also, from above, vb6 DOES “provides access to third-party controls like COM, DCOM ” That is not anything
new in .NET.

How to achieve Polymorphism in VB.Net?

We can achieve polymarphism in .Net i.e Compile time polymarphism and Runtime polymarphism. Compiletime Polymarphism achieved by
method overloading. Runtime polymarphism achieved by Early Binding or Late Binding. Provide the function pointer to the object at compile
time called as Early Binding. provide the function pointer to the object at runtime called as Late Binding class emp having the method display()
class dept having the method display()

create objects as in the main function // Early binding dim obj as new emp dim ob as new dept

obj.display()-to call the display method of emp class ob.display-to call the display method of the dept class // Late binding

create object in the main class as object obj obj=new emp obj.display()-to call the display of emp class obj=new dept obj.display()-to call the
display of dept class

Difference between Class And Interface

Class is logical representation of object. It is collection of data and related sub procedures with defination. Interface is also a class containg
methods which is not having any definations. Class does not support multiple inheritance. But interface can support.

What doesu mean by .NET framework?

The .NET Framework is an environment for building, deploying, and running Web Services and other applications. It consists of three main
parts: the Common Language Runtime, the Framework classes, and ASP.NET

What is assembly?

It is a single deployable unit that contains all the information abt the implimentation of classes , stuctures and interfaces NET framework
overview

1. Has own class libraries. System is the main namespace and all other namespaces are subsets of this. 2. It has CLR(Common language runtime,
Common type system, common language specification) 3. All the types are part of CTS and Object is the base class for all the types. 4. If a
language said to be .net complaint, it should be compatible with CTS and CLS. 5. All the code compiled into an intermediate language by the
.Net language compiler, which is nothing but an assembly. 6. During runtime, JIT of CLR picks the IL code and converts into PE machine code
and from there it processes the request. 7. CTS, CLS, CLR 8. Garbage Collection 9. Dispose, finalize, suppress finalize, Idispose interface 10.
Assemblies, Namespace: Assembly is a collection of class/namespaces. An assembly contains Manifest, Metadata, Resource files, IL code 11.
Com interoperability, adding references, web references 12. Database connectivity and providers

Application Domain 1. Class modifiers: public, private, friend, protected, protected friend, mustinherit, NotInheritable 2. Method modifiers:
public, private 3. Overridable 4. Shadows 5. Overloadable 6. Overrides 7. Overloads 8. Set/Get Property 9. IIF 10. Inheritance 11. Polymorphism
12. Delegates 13. Events 14. Reflection 15. Boxing 16. UnBoxing
ASP.Net 1. Web Controls: Data grid (templates, sorting, paging, bound columns, unbound columns, data binding), Data list, repeater controls 2.
HTML Controls 3. Code behind pages, system.web.ui.page base class 4. Web.config: App settings, identity (impersonate), authentication
(windows, forms, anonymous, passport), authorization 5. Databind.eval 6. Trace, Debug 7. Output cache 8. Session management 9. Application,
Session 10. Global.asax httpapplication 11. User controls, custom controls, custom rendered controls (postback event, postdatachanged event)
usercontrol is the base class 12. Directives

ADO.Net 1. Command object (ExecuteNonquery, ExecuteReader, ExecuteXMLReader, ExecuteScalar) 2. DataAdapter object (Fill) 3. Dataset
(collection of tables) 4. CommandBuiler object 5. Transaction Object 6. Isolation levels

.NET interview questions(81-90)


What is value?

Value is a ‘physical’ characteristic of the property. Property declares what should be formatted, e.g. FONT while value suggests how the property
should be formatted, e.g. 12pt. By setting the value 12pt to the property FONT it is suggested that the formatted text be displayed in a 12 point
font. There must always be a corresponding property to each value or set of values.

H1 {font: bold 180%} In the example above the H1 selector is declared the FONT property which in its turn is declared the values BOLD and
180%. The values suggesting alternatives are specified in a comma separated list, e.g. H1 {font-family: font1, font2}

What is initial value?

Initial value is a default value of the property, that is the value given to the root element of the document tree. All properties have an initial value.
If no specific value is set and/or if a property is not inherited the initial value is used. For example the background property is not inherited,
however, the background of the parent element shines through because the initial value of background property is transparent.

<P style="background: red">Hello <strong>World </strong> </P> Content of the element P will also have red background

How frustrating is it to write a specification knowing that you’re at the browser vendors’ mercy?

That’s part of the game. I don’t think any specification has a birthright to be fully supported by all browsers. There should be healthy competition
between different specifications. I believe simple, author-friendly specifications will prevail in this environment. Microformats are another way
of developing new formats. Instead of having to convince browser vendors to support your favorite specification, microformats add semantics to
HTML through the CLASS attribute. And style it with CSS.

How far can CSS be taken beyond the web page–that is, have generalized or non-web specific features for such things as page formatting
or type setting?

Yes, it’s possible to take CSS further in several directions. W3C just published a new Working Draft which describes features for printing, e.g.,
footnotes, cross-references, and even generated indexes. Another great opportunity for CSS is Web Applications. Just like documents,
applications need to be styled and CSS is an intrinsic component of AJAX. The “AJAX” name sounds great.

How To Style Table Cells?

Margin, Border and Padding are difficult to apply to inline elements. Officially, the tag is a block level element because it can contain other block
level elements (see Basics – Elements). If you need to set special margins, borders, or padding inside a table cell, then use this markup:

<td> yourtext </div> </td> to apply the CSS rules to the div inside the cell.

How To Style Forms?

Forms and form elements like SELECT, INPUT etc. can be styled with CSS – partially. Checkboxes and Radiobuttons do not yet accept styles,
and Netscape 4.xx has certain issues, but here is a tutorial that explains the application of CSS Styles on Form Elements.

How do I get my footer to sit at the bottom…?

Margin, Border and Padding are difficult to apply to inline elements. Officially, the tag is a block level element because it can contain other block
level elements (see Basics – Elements). If you need to set special margins, borders, or padding inside a table cell, then use this markup:

<td> yourtext </div> </td> to apply the CSS rules to the div inside the cell.
How To Style Forms? Forms and form elements like SELECT, INPUT etc. can be styled with CSS – partially. Checkboxes and Radiobuttons do
not yet accept styles, and Netscape 4.xx has certain issues, but here is a tutorial that explains the application of CSS Styles on Form Elements.

How do I get my footer to sit at the bottom…? Need a div which makes space at the bottom of the main page (inside the #wrap div). Then, the
footer (being inside #wrap) can be placed in that space by using absolute positioning. Like this :

CSS body, html { height:100%; } body { margin:0; padding:0; } #wrap { position:relative; width:780px; margin:auto; min-height:100%; } * html
#wrap { height:100%; } # clearfooter { height:50px; overflow:hidden; } #footer { position:absolute; bottom:0; width:100%; height:50px; }
HTML <div id="wrap"> ...content goes here... <div id="clearfooter"></div> <div id="footer">Footer</div> </div>

Can I attach more than one declaration to a selector?

Yes. If more than one declaration is attached to a selector they must appear in a semi colon separated list, e.g.;

Selector {declaration1; declaration2} P {background: white; color: black}

Border around a table?

Try the following:

.tblboda { border-width: 1px; border-style: solid; border-color: #CCCCCC; } /*color, thickness and style can be altered*/ You put this style
declaration either in an external stylesheet, or you can stuff it in the <head></head> section, like: <style type="text/css"> (here you can place
your styles) </style> and apply it to the table as follows: <div class="tblboda"> <table yaddayadda> <tr> <td>Content text and more
content</td> </tr> </table> </div>

That should give you a grey thin border around this table.

If you want the border to ’shrink wrap’ around the table, then you have to use the tag instead the tag. But that is not quite proper CSS or HTML,
because a is for inline elements. A table is not an inline element, therefore the correct tag is a

. If you play around with it a bit then you have a good chance to achieve what you want and still have correct HTML/CSS.

The other way would be that you apply the class .tblboda directly to the table (for IE and other contemporary browsers), like

and you define another class for each stylesheet: .tblboda2

In the NN4.xx stylesheet, you use the same properties as above, and in the IE and other contemporary browsers you carefully set all those
properties to default, like {border-style: none;}

Then you wrap the table in the

with the class .tblboda2 (NN4.xx does that) (IE a.o.c.b. don’t do anything, because the border-style is set to “none” = no border at all).

This way you have a table that is wrapped in a nice little border: .tblboda2 for NN4.xx, .tblboda for IE and other modern browsers.

Basic .NET and ASP.NET interview questions


Submitter said questions were asked in a US company hiring a Web developer.

Explain the .NET architecture.


How many languages .NET is supporting now? - When .NET was introduced it came with several languages. VB.NET, C#, COBOL and Perl,
etc. The site

DotNetLanguages.Net says 44 languages are supported.

How is .NET able to support multiple languages? - a language should comply with the Common Language Runtime standard to become a .NET
language. In .NET, code is compiled to Microsoft Intermediate Language (MSIL for short). This is called as Managed Code. This Managed code
is run in .NET environment. So after compilation to this IL the language is not a barrier. A code can call or use a function written in another
language.
How ASP .NET different from ASP? - Scripting is separated from the HTML, Code is compiled as a DLL, these DLLs can be executed on the
server.

Resource Files: How to use the resource files, how to know which language to use?

What is smart navigation? - The cursor position is maintained when the page gets refreshed due to the server side validation and the page gets
refreshed.

What is view state? - The web is stateless. But in ASP.NET, the state of a page is maintained in the in the page itself automatically. How? The
values are encrypted and saved in hidden controls. this is done automatically by the ASP.NET. This can be switched off / on for a single control

Explain the life cycle of an ASP .NET page.

How do you validate the controls in an ASP .NET page? - Using special validation controls that are meant for this. We have Range Validator,
Email Validator.

Can the validation be done in the server side? Or this can be done only in the Client side? - Client side is done by default. Server side validation
is also possible. We can switch off the client side and server side can be done.

How to manage pagination in a page? - Using pagination option in DataGrid control. We have to set the number of records for a page, then it
takes care of pagination by itself.

What is ADO .NET and what is difference between ADO and ADO.NET? - ADO.NET is stateless mechanism. I can treat the ADO.Net as a
separate in-memory database where in I can use relationships between the tables and select insert and updates to the database. I can update the
actual database as a batch.

DOT NET interview Q&A part 1


1. How many languages .NET is supporting now?

When .NET was introduced it came with several languages. VB.NET, C#, COBOL and Perl, etc. The site DotNetLanguages.Net says 44
languages are supported.

2. How is .NET able to support multiple languages?

A language should comply with the Common Language Runtime standard to become a .NET language. In .NET, code is compiled to Microsoft
Intermediate Language (MSIL for short). This is called as Managed Code. This Managed code is run in .NET environment. So after compilation
to this IL the language is not a barrier. A code can call or use a function written in another language.

3. How ASP .NET different from ASP?

Scripting is separated from the HTML, Code is compiled as a DLL, these DLLs can be executed on the server.

4. What is smart navigation?

The cursor position is maintained when the page gets refreshed due to the server side validation and the page gets refreshed.

5. What is view state?

The web is stateless. But in ASP.NET, the state of a page is maintained in the in the page itself automatically. How? The values are encrypted
and saved in hidden controls. this is done automatically by the ASP.NET. This can be switched off / on for a single control

DOT NET interview Q&A part 2


6. How do you validate the controls in an ASP .NET page?

Using special validation controls that are meant for this. We have Range Validator, Email Validator.

7. Can the validation be done in the server side? Or this can be done only in the Client side?

Client side is done by default. Server side validation is also possible. We can switch off the client side and server side can be done.

8. How to manage pagination in a page?

Using pagination option in DataGrid control. We have to set the number of records for a page, then it takes care of pagination by itself.
9. What is ADO .NET and what is difference between ADO and ADO.NET?

ADO.NET is stateless mechanism. I can treat the ADO.Net as a separate in-memory database where in I can use relationships between the tables
and select insert and updates to the database. I can update the actual database as a batch.

dot net interview questions part 2

Runtime Technical Questions Assemblies


What is an assembly?
An assembly is the primary building block of a .NET Framework application. It is a collection of functionality that is built, versioned, and
deployed as a single implementation unit (as one or more files). All managed types and resources are marked either as accessible only within
their implementation unit, or as accessible by code outside that unit. Assemblies are self-describing by means of their manifest, which is an
integral part of every assembly. The manifest: Establishes the assembly identity (in the form of a text name), version, culture, and digital
signature (if the assembly is to be shared across applications). Defines what files (by name and file hash) make up the assembly implementation.
Specifies the types and resources that make up the assembly, including which are exported from the assembly.
Itemizes the compile-time dependencies on other assemblies.
Specifies the set of permissions required for the assembly to run properly.
This information is used at run time to resolve references, enforce version binding policy, and validate the integrity of loaded assemblies. The
runtime can determine and locate the assembly for any running object, since every type is loaded in the context of an assembly. Assemblies are
also the unit at which code access security permissions are applied. The identity evidence for each assembly is considered separately when
determining what permissions to grant the code it
contains. The self-describing nature of assemblies also helps makes zero-impact install and XCOPY deployment feasible.

What are private assemblies and shared assemblies?


A private assembly is used only by a single application, and is stored in that application's install directory (or a subdirectory therein). A shared
assembly is one that can be referenced by more than one application. In order to share an assembly, the assembly must be explicitly built for this
purpose by giving it a cryptographically strong name (referred to as a strong name). By contrast, a private assembly name need only be unique
within the application that uses it. By making a distinction between private and shared assemblies, we introduce the notion of sharing as an
explicit decision. Simply by deploying private assemblies to an application directory, you can guarantee that that application will run only with
the bts it was built and deployed with. References to private assemblies will only be resolved locally to the private application directory.
There are several reasons you may elect to build and use shared assemblies, such as the ability to express version policy. The fact that shared
assemblies have a cryptographically strong name means that only the author of the assembly has the key to produce a new version of that
assembly. Thus, if you make a policy statement that says you want to accept a new version of an assembly, you can have some confidence that
version updates will be controlled and verified by the author. Otherwise, you don't have to accept them. For locally installed applications, a
shared assembly is typically explicitly installed into the global assembly cache (a local cache of assemblies maintained by the .NET Framework).
Key to the version management features of the .NET Framework is that downloaded code does not affect the execution of locally installed
applications. Downloaded code is put in a special download cache and is not globally available on the machine even if some of the downloaded
components are built as shared assemblies.
The classes that ship with the .NET Framework are all built as shared assemblies.

dot net interview questions part 3

Runtime Technical Questions

Assemblies

If I want to build a shared assembly, does that require the overhead of signing and
managing key pairs?

Building a shared assembly does involve working with cryptographic keys. Only the public key is strictly needed when the assembly is being
built. Compilers targeting the .NET Framework provide command line options (or use custom attributes) for supplying the public key when
building the assembly. It is common to keep a copy of a common public key in a source database and point build scripts to this key. Before the
assembly is shipped, the assembly must be fully signed with the corresponding private key. This is done using an SDK tool called SN.exe (Strong
Name).
Strong name signing does not involve certificates like Authenticode does. There are no third party organizations involved, no fees to pay, and no
certificate chains. In addition, the overhead for verifying a strong name is much less than it is for Authenticode. However, strong names do not
make any statements about trusting a particular publisher. Strong names allow you to ensure that the contents of a given assembly haven't been
tampered with, and that the assembly loaded on your behalf at run time comes from the same publisher as the one you developed against. But it
makes no statement about whether you can trust the identity of that publisher.

What is the difference between a namespace and an assembly name?


A namespace is a logical naming scheme for types in which a simple type name, such as MyType, is preceded with a dot-separated hierarchical
name. Such a naming scheme is completely under the control of the developer. For example, types MyCompany.FileAccess.A and
MyCompany.FileAccess.B might be logically expected to have functionality related to file access. The .NET Framework uses a hierarchical
naming scheme for grouping types into logical categories of related functionality, such as the Microsoft® ASP.NET application framework, or
remoting functionality. Design tools can make use of namespaces to make it easier for developers to browse and reference types in their code.
The concept of a namespace is not related to that of an assembly. A single assembly may contain types whose hierarchical names have different
namespace roots, and a logical namespace root may span multiple assemblies. In the .NET Framework, a namespace is a logical design-time
naming convenience, whereas an assembly establishes the name scope for types at run time.

dot net interview question part 10

19. What is a Manifest?

An assembly manifest contains all the metadata needed to specify the assembly's version requirements and security identity, and all metadata
needed to define the scope of the assembly and resolve references to resources and classes. The assembly manifest can be stored in either a PE
(Portable Executable) file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a standalone PE (Portable Executable) file
that contains only assembly manifest information. The following table shows the information contained in the assembly manifest. The first four
items the assembly name, version number, culture, and strong name information make up the assembly's identity. Assembly name: A text string
specifying the assembly's name. Version number: A major and minor version number, and a revision and build number. The common language
runtime uses these numbers to enforce version policy.
Culture: Information on the culture or language the assembly supports. This information should be used only to designate an assembly as a
satellite assembly containing culture- or language-specific information. (An assembly with culture information is automatically assumed to be a
satellite assembly.) Strong name information: The public key from the publisher if the assembly has been given a strong name. List of all files in
the assembly: A hash of each file contained in the assembly and a file name. Note that all files that make up the assembly must be in the same
directory as the file containing the assembly manifest. Type reference information: Information used by the runtime to map a type reference to
the file that contains its declaration and implementation. This is used for types that are exported from the assembly.
Information on referenced assemblies: A list of other assemblies that are statically referenced by the assembly. Each reference includes the
dependent assembly's name, assembly metadata (version, culture, operating system, and so on), and public key, if the assembly is strong named.

dot net interview questions part 11

20. Creating a Key Pair?

You can create a key pair using the Strong Name tool (Sn.exe). Key pair files usually have an .snk extension. To create a key pair At the
command prompt, type the following command:
sn k
In this command, file name is the name of the output file containing the key pair. The following example creates a key pair called sgKey.snk.
sn -k sgKey.snk

21. What is the difference between "using System.Data;" and directly adding the reference from "Add References Dialog Box"?

When u compile a program using command line, u add the references using /r switch. When you compile a program using Visual Studio, it adds
those references to our assembly, which are added using "Add Reference" dialog box. While "using" statement facilitates us to use classes
without using their fully qualified names.
For example: if u have added a reference to "System.Data.SqlClient" using "Add Reference" dialog box then u can use SqlConnection class like
this:
System.Data.SqlClient.SqlConnection
But if u add a "using System.Data.SqlClient" statement at the start of ur code then u can directly use SqlConnection class.
On the other hand if u add a reference using "using System.Data.SqlClient" statement, but don't add it using "Add Reference" dialog box, Visual
Studio will give error message while we compile the program.

22. What is GAC?

The global assembly cache stores assemblies specifically designated to be shared by several applications on the computer. You should share
assemblies by installing them into the global assembly cache only when you need to. Assemblies deployed in the global assembly cache must
have a strong name. When an assembly is added to the global assembly cache, integrity checks are performed on all files that make up the
assembly. The cache performs these integrity checks to ensure that an assembly has not been tampered with, for example, when a file has
changed but the manifest does not reflect the change. Use a developer tool called the Global Assembly Cache tool (Gacutil.exe), provided by
the .NET Framework SDK or Use Windows Explorer to drag assemblies into the cache. To install a strong-named assembly into the global
assembly cache At the command prompt, type the following command:
gacutil I
In this command, assembly name is the name of the assembly to install in the global assembly cache.
dot interview questions part 12

23. What is a Metadata?

Metadata is information about a PE. In COM, metadata is communicated through non-standardized type libraries. In .NET, this data is contained
in the header portion of a COFF-compliant PE and follows certain guidelines; it contains information such as the assembly’s name, version,
language (spoken, not computera.k.a., culture), what external types are referenced, what internal types are exposed, methods, properties, classes,
and much more. The CLR uses metadata for a number of specific purposes. Security is managed through a public key in the PE’s header.
Information about classes, modules, and so forth allows the CLR to know in advance what structures are necessary. The class loader component
of the CLR uses metadata to locate specific classes within assemblies, either locally or across networks. Just-in-time (JIT) compilers use the
metadata to turn IL into executable code. Other programs take advantage of metadata as well. A common example is placing a Microsoft Word
document on a Windows 2000 desktop. If the document file has completed comments, author, title, or other Properties metadata, the text is
displayed as a tool tip when a user hovers the mouse over the document on the desktop. You can use the Ildasm.exe utility to view the metadata
in a PE. Literally, this tool is an IL disassembler.

24. What is managed code and managed data?

Managed code is code that is written to target the services of the Common Language Runtime. In order to target these services, the code must
provide a minimum level of information (metadata) to the runtime. All C#, Visual Basic .NET, and JScript .NET code is managed by default.
Visual Studio .NET C++ code is not managed by default, but the compiler can produce managed code by specifying a command-line switch
(/CLR). Closely related to managed code is managed data--data that is allocated and de- allocated by the Common Language Runtime's garbage
collector. C#, Visual Basic, and JScript .NET data is managed by default. C# data can, however, be marked as unmanaged through the use of
special keywords. Visual Studio .NET C++ data is unmanaged by default (even when using the /CLR switch), but when using Managed
Extensions for C++, a class can be marked as managed using the __gc keyword. As the name suggests, this means that the memory for instances
of the class is managed by the garbage collector. In addition, the class becomes a full participating member of the .NET Framework community,
with the benefits and restrictions that it brings. An example of a benefit is proper interoperability with classes written in other languages (for
example, a managed C++ class can inherit from a Visual Basic class). An example of a restriction is that a managed class can only inherit from
one base class.

dot net interview questions part 17


40. What is Delegation?

A delegate acts like a strongly type function pointer. Delegates can invoke the methods that they reference without making explicit calls to those
methods.
Delegate is an entity that is entrusted with the task of representation, assign or passing on information. In code sense, it means a Delegate is
entrusted with a Method to report information back to it when a certain task (which the Method expects) is accomplished outside the Method's
class.

41. What is "Microsoft Intermediate Language" (MSIL)?

A .NET programming language (C#, VB.NET, J# etc.) does not compile into executable code; instead it compiles into an intermediate code
called Microsoft Intermediate Language (MSIL). As a programmer one need not worry about the syntax of MSIL - since our source code in
automatically converted to MSIL. The MSIL code is then send to the CLR (Common Language Runtime) that converts the code to machine
language, which is, then run on the host machine. MSIL is similar to Java Byte code. MSIL is the CPU-independent instruction set into which
.NET Framework programs are compiled. It contains instructions for loading, storing, initializing, and calling methods on objects. Combined
with metadata and the common type system, MSIL allows for true cross- language integration Prior to execution, MSIL is converted to machine
code. It is not interpreted.

42. Differences between Datagrid, Datalist and Repeater?

1. Datagrid has paging while Datalist doesnt.


2. Datalist has a property called repeat. Direction = vertical/horizontal. (This is of great help in designing layouts). This is not there in Datagrid.
3. A repeater is used when more intimate control over html generation is required.
4. When only checkboxes/radiobuttons are repeatedly served then a checkboxlist or radiobuttonlist are used as they involve fewer overheads than
a Datagrid.
The Repeater repeats a chunk of HTML you write, it has the least functionality of the three. DataList is the next step up from a Repeater; accept
you have very little control over the HTML that the control renders. DataList is the first of the three controls that allow you Repeat-Columns
horizontally or vertically. Finally, the DataGrid is the motherload. However, instead of working on a row-by-row basis, you’re working on a
column-by-column basis. DataGrid caters to sorting and has basic paging for your disposal. Again you have little contro, over the HTML. NOTE:
DataList and DataGrid both render as HTML tables by default. Out of the 3 controls, I use the Repeater the most due to its flexibility w/ HTML.
Creating a Pagination scheme isn't that hard, so I rarely if ever use a DataGrid.
Occasionally I like using a DataList because it allows me to easily list out my records in rows of three for instance

dot net interview Q&A part 1


1. How many languages .NET is supporting now?

When .NET was introduced it came with several languages. VB.NET, C#, COBOL and Perl, etc. The site DotNetLanguages.Net says 44
languages are supported.

2. How is .NET able to support multiple languages?

A language should comply with the Common Language Runtime standard to become a .NET language. In .NET, code is compiled to Microsoft
Intermediate Language (MSIL for short). This is called as Managed Code. This Managed code is run in .NET environment. So after compilation
to this IL the language is not a barrier. A code can call or use a function written in another language.

3. How ASP .NET different from ASP?

Scripting is separated from the HTML, Code is compiled as a DLL, these DLLs can be executed on the server.

4. What is smart navigation?

The cursor position is maintained when the page gets refreshed due to the server side validation and the page gets refreshed.

5. What is view state?

The web is stateless. But in ASP.NET, the state of a page is maintained in the in the page itself automatically. How? The values are encrypted
and saved in hidden controls. this is done automatically by the ASP.NET. This can be switched off / on for a single control

dot net interview Q&A part 2


6. How do you validate the controls in an ASP .NET page?

Using special validation controls that are meant for this. We have Range Validator, Email Validator.

7. Can the validation be done in the server side? Or this can be done only in the Client side?

Client side is done by default. Server side validation is also possible. We can switch off the client side and server side can be done.

8. How to manage pagination in a page?

Using pagination option in DataGrid control. We have to set the number of records for a page, then it takes care of pagination by itself.

9. What is ADO .NET and what is difference between ADO and ADO.NET?

ADO.NET is stateless mechanism. I can treat the ADO.Net as a separate in-memory database where in I can use relationships between the tables
and select insert and updates to the database. I can update the actual database as a batch.

dot net interview Q&A part 3


11. Observations between VB.NET and VC#.NET?

Choosing a programming language depends on your language experience and the scope of the application you are building. While small
applications are often created using only one language, it is not uncommon to develop large applications using multiple languages.
For example, if you are extending an application with existing XML Web services, you might use a scripting language with little or no
programming effort. For client-server applications, you would probably choose the single language you are most comfortable with for the entire
application. For new enterprise applications, where large teams of developers create components and services for deployment across multiple
remote sites, the best choice might be to use several languages depending on developer skills and long-term maintenance expectations.
The .NET Platform programming languages - including Visual Basic .NET, Visual C#, and Visual C++ with managed extensions, and many
other programming languages from various vendors - use .NET Framework services and features through a common set of unified classes.
The .NET unified classes provide a consistent method of accessing the platform's functionality. If you learn to use the class library, you will find
that all tasks follow the same uniform architecture. You no longer need to learn and master different API architectures to write your applications.
In most situations, you can effectively use all of the Microsoft programming languages. Nevertheless, each programming language has its relative
strengths and you will want to understand the features unique to each language. The following sections will help you choose the right
programming language for your application.
Visual Basic .NET
Visual Basic .NET is the next generation of the Visual Basic language from Microsoft. With Visual Basic you can build .NET applications,
including Web services and ASP.NET Web applications, quickly and easily. Applications made with Visual Basic are built on the services of the
common language runtime and take advantage of the .NET Framework.
Visual Basic has many new and improved features such as inheritance, interfaces, and overloading that make it a powerful object-oriented
programming language. Other new language features include free threading and structured exception handling. Visual Basic fully integrates
the .NET Framework and the common language runtime, which together provide language interoperability, garbage collection, enhanced
security, and improved versioning support. A Visual Basic support single inheritance and creates Microsoft intermediate language (MSIL) as
input to native code compilers.
Visual Basic is comparatively easy to learn and use, and Visual Basic has become the programming language of choice for hundreds of thousands
of developers over the past decade. An understanding of Visual Basic can be leveraged in a variety of ways, such as writing macros in Visual
Studio and providing programmability in applications such as Microsoft Excel, Access, and Word.
Visual Basic provides prototypes of some common project types, including:
• Windows Application.
• Class Library.
• Windows Control Library.
• ASP.NET Web Application.
• ASP.NET Web Service.
• Web Control Library.
• Console Application.
• Windows Service.
• Windows Service.
Visual C# .NET
Visual C# (pronounced C sharp) is designed to be a fast and easy way to create .NET applications, including Web services and ASP.NET Web
applications. Applications written in Visual C# are built on the services of the common language runtime and take full advantage of the .NET
Framework.
C# is a simple, elegant, type-safe, object-oriented language recently developed by Microsoft for building a wide range of applications. Anyone
familiar with C and similar languages will find few problems in adapting to C#. C# is designed to bring rapid development to the C++
programmer without sacrificing the power and control that are a hallmark of C and C++. Because of this heritage, C# has a high degree of fidelity
with C and C++, and developers familiar with these languages can quickly become productive in C#. C# provides intrinsic code trust
mechanisms for a high level of security, garbage collection, and type safety. C# supports single inheritance and creates Microsoft intermediate
language (MSIL) as input to native code compilers.
C# is fully integrated with the .NET Framework and the common language runtime, which together provide language interoperability, garbage
collection, enhanced security, and improved versioning support. C# simplifies and modernizes some of the more complex aspects of C and C++,
notably namespaces, classes, enumerations, overloading, and structured exception handling. C# also eliminates C and C++ features such as
macros, multiple inheritance, and virtual base classes. For current C++ developers, C# provides a powerful, high-productivity language
alternative.
Visual C# provides prototypes of some common project types, including:
• Windows Application.
• Class Library.
• Windows Control Library.
• ASP.NET Web Application.
• ASP.NET Web Service.
• Web Control Library.
• Console Application.
• Windows Service.

dot net interview Q&A part 4


12. Advantages of migrating to VB.NET ?

Visual Basic .NET has many new and improved language features — such as inheritance, interfaces, and overloading that make it a powerful
object-oriented programming language. As a Visual Basic developer, you can now create multithreaded, scalable applications using explicit
multithreading. Other new language features in Visual Basic .NET include structured exception handling, custom attributes, and common
language specification (CLS) compliance.

The CLS is a set of rules that standardizes such things as data types and how objects are exposed and interoperate. Visual Basic .NET adds
several features that take advantage of the CLS. Any CLS-compliant language can use the classes, objects, and components you create in Visual
Basic .NET. And you, as a Visual Basic user, can access classes, components, and objects from other CLS-compliant programming languages
without worrying about language-specific differences such as data types. CLS features used by Visual Basic .NET programs include assemblies,
namespaces, and attributes. These are the new features to be stated briefly:

Inheritance
Visual Basic .NET supports inheritance by allowing you to define classes that serve as the basis for derived classes. Derived classes inherit and
can extend the properties and methods of the base class. They can also override inherited methods with new implementations. All classes created
with Visual Basic .NET are inheritable by default. Because the forms you design are really classes, you can use inheritance to define new forms
based on existing ones.

Exception Handling
Visual Basic .NET supports structured exception handling, using an enhanced version of the Try...Catch...Finally syntax supported by other
languages such as C++.
Structured exception handling combines a modern control structure (similar to Select Case or While) with exceptions, protected blocks of code,
and filters. Structured exception handling makes it easy to create and maintain programs with robust, comprehensive error handlers.

Overloading
Overloading is the ability to define properties, methods, or procedures that have the same name but use different data types. Overloaded
procedures allow you to provide as many implementations as necessary to handle different kinds of data, while giving the appearance of a single,
versatile procedure. Overriding Properties and Methods The Overrides keyword allows derived objects to override characteristics inherited from
parent objects. Overridden members have the same arguments as the members inherited from the base class, but different implementations. A
member's new implementation can call the original implementation in the parent class by preceding the member name with MyBase.

Constructors and Destructors


Constructors are procedures that control initialization of new instances of a class. Conversely, destructors are methods that free system resources
when a class leaves scope or is set to Nothing. Visual Basic .NET supports constructors and destructors using the Sub New and Sub Finalize
procedures.

Data Types
Visual Basic .NET introduces three new data types. The Char data type is an unsigned 16-bit quantity used to store Unicode characters. It is
equivalent to the .NET Framework System. Char data type. The Short data type, a signed 16-bit integer, was named Integer in earlier versions of
Visual Basic. The Decimal data type is a 96-bit signed integer scaled by a variable power of 10. In earlier versions of Visual Basic, it was
available only within a Variant.

Interfaces
Interfaces describe the properties and methods of classes, but unlike classes, do not provide implementations. The Interface statement allows you
to declare interfaces, while the Implements statement lets you write code that puts the items described in the interface into practice.

Delegates
Delegates objects that can call the methods of objects on your behalf are sometimes described as type-safe, object-oriented function pointers. You
can use delegates to let procedures specify an event handler method that runs when an event occurs. You can also use delegates with
multithreaded applications. For details, see Delegates and the AddressOf Operator.

Shared Members
Shared members are properties, procedures, and fields that are shared by all instances of a class. Shared data members are useful when multiple
objects need to use information that is common to all. Shared class methods can be used without first creating an object from a class.

References
References allow you to use objects defined in other assemblies. In Visual Basic .NET, references point to assemblies instead of type libraries.
For details, see References and the Imports Statement. Namespaces Namespaces prevent naming conflicts by organizing classes, interfaces, and
methods into hierarchies.

Assemblies
Assemblies replace and extend the capabilities of type libraries by, describing all the required files for a particular component or application. An
assembly can contain one or more namespaces.

Attributes
Attributes enable you to provide additional information about program elements. For example, you can use an attribute to specify which methods
in a class should be exposed when the class is used as a XML Web service. Multithreading
Visual Basic .NET allows you to write applications that can perform multiple tasks independently. A task that has the potential of holding up
other tasks can execute on a separate thread, a process known as multithreading. By causing complicated tasks to run on threads that are separate
from your user interface, multithreading makes your applications more responsive to user input.

dot net interview Q&A part 5


13. Advantages of VB.NET

First of all, VB.NET provides managed code execution that runs under the Common Language Runtime (CLR), resulting in robust, stable and
secure applications. All features of the .NET framework are readily available in VB.NET.
VB.NET is totally object oriented. This is a major addition that VB6 and other earlier releases didn't have.
The .NET framework comes with ADO.NET, which follows the disconnected paradigm, i.e. once the required records are fetched the connection
no longer exists. It also retrieves the records that are expected to be accessed in the immediate future. This enhances Scalability of the application
to a great extent.
VB.NET uses XML to transfer data between the various layers in the DNA Architecture i.e. data are passed as simple text strings.
Error handling has changed in VB.NET. A new Try-Catch-Finally block has been introduced to handle errors and exceptions as a unit, allowing
appropriate action to be taken at the place the error occurred thus discouraging the use of ON ERROR GOTO statement. This again credits to the
maintainability of the code.
Another great feature added to VB.NET is free threading against the VB single-threaded apartment feature. In many situations developers need
spawning of a new thread to run as a background process and increase the usability of the application. VB.NET allows developers to spawn
threads wherever they feel like, hence giving freedom and better control on the application.
Security has become more robust in VB.NET. In addition to the role-based security in VB6, VB.NET comes with a new security model, Code
Access security. This security controls on what the code can access. For example you can set the security to a component such that the
component cannot access the database. This type of security is important because it allows building components that can be trusted to various
degrees.
The CLR takes care of garbage collection i.e. the CLR releases resources as soon as an object is no more in use. This relieves the developer from
thinking of ways to manage memory. CLR does this for them.

dot net interview Q&A part 6

14. Using ActiveX Control in .Net

ActiveX control is a special type of COM component that supports a User Interface. Using ActiveX Control in your .Net Project is even easier
than using COM component. They are bundled usually in .ocx files. Again a proxy assembly is made by .Net utility AxImp.exe (which we will
see shortly) which your application (or client) uses as if it is a .Net control or assembly.
Making Proxy Assembly For ActiveX Control: First, a proxy assembly is made using AxImp.exe (acronym for ActiveX Import) by writing
following command on Command Prompt:
C:>AxImp C:MyProjectsMyControl.ocx
This command will make two dlls, e.g., in case of above command
MyControl.dll
AxMyControl.dll
The first file MyControl.dll is a .Net assembly proxy, which allows you to reference the ActiveX as if it were non-graphical object.
The second file AxMyControl.dll is the Windows Control, which allows u to use the graphical aspects of activex control and use it in the
Windows Form Project.
Adding Reference of ActiveX Proxy Assembly in your Project Settings: To add a reference of ActiveX Proxy Assembly in our Project, do this:
o Select ProjectàAdd Reference (Select Add Reference from Project Menu).
o This will show you a dialog box, select .Net tab from the top of window.
o Click Browse button on the top right of window.
o Select the dll file for your ActiveX Proxy Assembly (which is MyControl.dll) and click OK o Your selected component is now shown in the
‘Selected Component’ List Box. Click OK again Some More On Using COM or ActiveX in .Net
.Net only provides wrapper class or proxy assembly (Runtime Callable Wrapper or RCW) for COM or activeX control. In the background, it is
actually delegating the tasks to the original COM, so it does not convert your COM/activeX but just imports them.
A good thing about .Net is that when it imports a component, it also imports the components that are publically referenced by that component.
So, if your component, say MyDataAcsess.dll references ADODB.dll then .Net will automatically import that COM component too!
The Visual Studio.NET does surprise you in a great deal when u see that it is applying its intellisense (showing methods, classes, interfaces,
properties when placing dot) even on your imported COM components!!!! Isn’t it a magic or what?
When accessing thru RCW, .Net client has no knowledge that it is using COM component, it is presented just as another C# assembly.
U can also import COM component thru command prompt (for reference see Professional C# by Wrox) U can also use your .Net components in
COM, i.e., export your .net components (for reference see Professional C# by Wrox)

dot net interview Q&A part 7

15. What is Machine.config?

Machine configuration file: The machine.config file contains settings that apply to the entire computer. This file is located in the %runtime install
path%Config directory. There is only one machine.config file on a computer. The Machine.Config file found in the "CONFIG" subfolder of
your .NET Framework install directory (c:WINNTMicrosoft.NETFramework{Version Number}CONFIG on Windows 2000 installations). The
machine.config, which can be found in the directory $WINDIR$Microsoft.NETFrameworkv1.0.3705CONFIG, is an XML-formatted
configuration file that specifies configuration options for the machine. This file contains, among many other XML elements, a browserCaps
element. Inside this element are a number of other elements that specify parse rules for the various User-Agents, and what properties each of
these parsings supports.
For example, to determine what platform is used, a filter element is used that specifies how to set the platform property based on what platform
name is found in the User-Agent string. Specifically, the machine.config file contains:
platform=Win95
platform=Win98
platform=WinNT
...
That is, if in the User-Agent string the string "Windows 95" or "Win95" is found, the platform property is set to Win95. There are a number of
filter elements in the browserCaps element in the machine.config file that define the various properties for various User-Agent strings.
Hence, when using the Request.Browser property to determine a user's browser features, the user's agent string is matched up to particular
properties in the machine.config file. The ability for being able to detect a user's browser's capabilities, then, is based upon the honesty in the
browser's sent User-Agent string. For example, Opera can be easily configured to send a User-Agent string that makes it appear as if it's IE 5.5.
In this case from the Web server's perspective (and, hence, from your ASP.NET Web page's perspective), the user is visiting using IE 5.5, even
though, in actuality, he is using Opera.

16. What is Web.config?

In classic ASP all Web site related information was stored in the metadata of IIS. This had the disadvantage that remote Web developers couldn't
easily make Web-site configuration changes. For example, if you want to add a custom 404 error page, a setting needs to be made through the IIS
admin tool, and you're Web host will likely charge you a flat fee to do this for you. With ASP.NET, however, these settings are moved into an
XML-formatted text file (Web.config) that resides in the Web site's root directory. Through Web.config you can specify settings like custom 404
error pages, authentication and authorization settings for the Web sitempilation options for the ASP.NET Web pages, if tracing should be
enabled, etc.
The Web.config file is an XML-formatted file. At the root level is the tag. Inside this tag you can add a number of other tags, the most common
and useful one being the system.web tag, where you will specify most of the Web site configuration parameters. However, to specify application-
wide settings you use the tag.
For example, if we wanted to add a database connection string parameter we could have a Web.config file like so.

dot net interview Q&A part 8

17. What is the difference between ADO and ADO.NET?

ADO uses Recordsets and cursors to access and modify data. Because of its inherent design, Recordset can impact performance on the server side
by tying up valuable resources. In addition, COM marshalling - an expensive data conversion process - is needed to transmit a Recordset.
ADO.NET addresses three important needs that ADO doesn't address:
1. Providing a comprehensive disconnected data-access model, which is crucial to the Web environment
2. Providing tight integration with XML, and
3. Providing seamless integration with the .NET Framework (e.g., compatibility with the base class library's type system). From an ADO.NET
implementation perspective, the Recordset object in ADO is eliminated in the .NET architecture. In its place, ADO.NET has several dedicated
objects led by the DataSet object and including the DataAdapter, and DataReader objects to perform specific tasks. In addition, ADO.NET
DataSets operate in disconnected state whereas the ADO RecordSet objects operated in a fully connected state.
In ADO, the in-memory representation of data is the recordset. In ADO.NET, it is the dataset. A recordset looks like a single table. If a recordset
is to contain data from multiple database tables, it must use a JOIN query, which assembles the data from the various database tables into a single
result table. In contrast, a dataset is a collection of one or more tables. The tables within a dataset are called data tables; specifically, they are
DataTable objects. If a dataset contains data from multiple database tables, it will typically contain multiple DataTable objects. That is, each
DataTable object typically
corresponds to a single database table or view. In this way, a dataset can mimic the structure of the underlying database. In ADO you scan
sequentially through the rows of the recordset using the ADO MoveNext method. In ADO.NET, rows are represented as collections, so you can
loop through a table as you would through any collection, or access particular rows via ordinal or primary key index. A cursor is a database
element that controls record navigation, the ability to update data, and the visibility of changes made to the database by other users. ADO.NET
does not have an inherent cursor object, but instead includes data classes that provide the functionality of a traditional cursor. For example, the
functionality of a forward-only, read-only cursor is available in the ADO.NET DataReader object.
There is one significant difference between disconnected processing in ADO and ADO.NET. In ADO you communicate with the database by
making calls to an OLE DB provider. In ADO.NET you communicate with the database through a data adapter (an OleDbDataAdapter,
SqlDataAdapter, OdbcDataAdapter, or OracleDataAdapter object), which makes calls to an OLE DB provider or the APIs provided by the
underlying data source.
dot net interview Q&A part 9

17. What is the difference between VB and VB.NET?

Now VB.NET is object-oriented language. The following are some of the differences:
Data Type Changes
The .NET platform provides Common Type System to all the supported languages. This means that all the languages must support the same data
types as enforced by common language runtime. This eliminates data type incompatibilities between various languages. For example on the 32-
bit Windows platform, the integer data type takes 4 bytes in languages like C++ whereas in VB it takes 2 bytes. Following are the main changes
related to data types in VB.NET:
. Under .NET the integer data type in VB.NET is also 4 bytes in size.
. VB.NET has no currency data type. Instead it provides decimal as a replacement.
. VB.NET introduces a new data type called Char. The char data type takes 2 bytes and can store Unicode characters.
. VB.NET do not have Variant data type. To achieve a result similar to variant type you can use Object data type. (Since every thing in .NET
including primitive data types is an object, a variable of object type can point to any data type).
. In VB.NET there is no concept of fixed length strings.
. In VB6 we used the Type keyword to declare our user-defined structures. VB.NET introduces the structure keyword for the same purpose.
Declaring Variables
Consider this simple example in VB6:
Dim x,y as integer
In this example VB6 will consider x as variant and y as integer, which is somewhat odd behavior. VB.NET corrects this problem, creating both x
and y as integers.
Furthermore, VB.NET allows you to assign initial values to the variables in the declaration statement itself:
Dim str1 as string = Hello
VB.NET also introduces Read-Only variables. Unlike constants Read-Only variables can be declared without initialization but once you assign a
value to it, it cannot be changes.
Initialization here
Dim readonly x as integer
In later code
X=100
Now x can’t be changed
X=200 *********** Error **********
Property Syntax
In VB.NET, we anymore don't have separate declarations for Get and Set/Let. Now, everything is done in a single property declaration. This can
be better explained by the following example.
Public [ReadOnly | WriteOnly] Property PropertyName as Datatype
Get
Return m_var
End Get
Set
M_var = value
End Set
End Property
Example:
Private _message as String
Public Property Message As String
Get
Return _message
End Get
Set
_message = Value
End Set
End Property
ByVal is the default - This is a crucial difference betwen VB 6.0 and VB.NET, where the default in VB 6.0 was by reference. But objects are still
passed by reference.
Invoking Subroutines In previous versions of VB, only functions required the use of parentheses around the parameter list. But in VB.NET all
function or subroutine calls require parentheses around the parameter list. This also applies, even though the parameter list is empty.
User-Defined Types - VB.NET does away with the keyword Type and replaces it with the keyword Structure
Public Structure Student
Dim strName as String
Dim strAge as Short
End Structure
Procedures and Functions
In VB6 all the procedure parameters are passed by reference (ByRef) by default. In VB.NET they are passed by value (ByVal) by default.
Parantheses are required for calling procedures and functions whether they accept any parameters or not. In VB6 functions returned values using
syntax like: FuntionName = return_value. In VB.NET you can use the Return keyword (Return return_value) to return values or you can
continue to use the older syntax, which is still valid.
Scoping VB.NET now supports block-level scoping of variables. If your programs declare all of the variables at the beginning of the function or
subroutine, this will not be a problem. However, the following VB 6.0 will cause an issue while upgrading to VB .NET
Do While objRs.Eof
Dim J as Integer
J=0
If objRs("flag")="Y" then
J=1
End If
objRs.MoveNext
Wend
If J Then
Msgbox "Flag is Y"
End If
In the above example the variable J will become out of scope just after the loop, since J was declared inside the While loop.
Exception Handling
The most wanted feature in earlier versions of VB was its error handling mechanism. The older versions relied on error handlers such as "On
Error GoTo and On Error Resume Next. VB.NET provides us with a more stuructured approach. The new block structure allows us to track the
exact error at the right time. The new error handling mechanism is refered to as Try...Throw...Catch...Finally. The following example will explain
this new feature.
Sub myOpenFile()
Try
Open "myFile" For Output As #1
Write #1, myOutput
Catch
Kill "myFile"
Finally
Close #1
End try
End Sub
The keyword SET is gone - Since everything in VB.NET is an object. So the keyword SET is not at all used to differentiate between a simple
variable assignment and an object assignment. So, if you have the following statement in VB 6.0
Set ObjConn = Nothing
Should be replaced as
ObjConn = Nothing.
Constructor and Destructor
The constructor procedure is one of the many new object-oriented features of VB.NET. The constructor in VB.NET replaces the Class_Initialize
in VB 6.0. All occurance of Class_Initialize in previous versions of VB should now be placed in a class constructor. In VB.NET, a constructor is
added to a class by adding a procedure called New. We can also create a class destructor, which is equivalent to Class_Terminate event in VB
6.0, by adding a sub-procedure called Finalize to our class. Usage of Return In VB.NET, we can use the keyword return to return a value from
any function. In previous versions, we used to assign the value back with the help of the function name itself. The following example explains
this:
Public Function Sum (intNum1 as Integer, intNum2 as Integer) as Integer
Dim intSum as Integer
intSum = intNum1 + intNum2
Return intSum
End Function
Static Methods
VB.NET now allows you to create static methods in your classes. Static methods are methods that can be called without requiring the developer
to create instance of the class. For example, if you had a class named Foo with the non-static method NonStatic() and the static method Static(),
you could call the Static() method like so:
Foo.Static()
However, non-static methods require than an instance of the class be created, like so:
Create an instance of the Foo class
Dim objFoo as New Foo()
Execute the NonStatic() method
ObjFoo.NonStatic()
To create a static method in a VB.NET, simply prefix the method definition with the keyword Shared.

dot net interview Q&A part 16

35. Using COM Component in .Net

As most of you know that .Net does not encourage the development of COM components and provides a different solution to making reusable
components through Assemblies. But, there are a lot of COM components present which our .Net application might need to use. Fortunately, .Net
provides an extremely simple approach to achieve this. This is achieved by using ‘Wrapper Classes’ and ‘Proxy Components’. .Net wraps the
COM component into .Net assembly technically called ‘Runtime Callable Wrapper’ or RCW. Then u can call and use your COM component just
as a .Net (or C#, if u are using C#) Assembly.

36. What is an assembly?

An assembly is the primary building block of a .NET Framework application. It is a collection of functionality that is built, versioned, and
deployed as a single implementation unit (as one or more files). All managed types and resources are marked either as accessible only within
their implementation unit, or as accessible by code outside that unit. .NET Assembly contains all the metadata about the modules, types, and
other elements it contains in the form of a manifest. The CLR loves assemblies because differing programming languages are just perfect for
creating certain kinds of applications. For example, COBOL stands for Common Business-Oriented Language because it’s tailor-made for
creating business apps. However, it’s not much good for creating drafting programs. Regardless of what language you used to create your
modules, they can all work together within one Portable Executable Assembly. There’s a hierarchy to the structure of .NET code. That hierarchy
is Assembly - > Module -> Type -> Method." Assemblies can be static or dynamic. Static assemblies can include .NET Framework types
(interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files, and so on). Static assemblies are stored on disk
in portable executable (PE) files. You can also use the .NET Framework to create dynamic assemblies, which are run directly from memory and
are not saved to disk before execution. You can save dynamic assemblies to disk after they have executed.

37. What is a Web Service?

A web service is a software component that exposes itself through the open communication channels of the Internet. Applications running on
remote machines, on potentially different platforms, can access these components in a language and platform-independent manner. A Web
Service is a group of functions, packaged together for use in a common framework throughout a network.

Dot Net Questions


what is clr?
what is manifest?
where is the version stored in an assembly?
Types of JIT?
what is satellite assembly?
what is boxing and unboxing?
Code access security?
what is IUKNOWN interface?
What is thread.sleep()?
what are locks and thier types?
what is remoting?
what are the advantages of dot net 3.5?
what is WCF and WPF?
what is DISCO?
what is WSDL?
what is UDDI?
wat is hosting?
extension of webservices?
what is cache callback?
types of caching?
hidden files?
what is hash table?
difference between client side coding and server side code?
where should validations be provided?client or server?
form authentication?
how to implement MVC pattern is .net?

dot net questions(3)


121. What's different about namespace declaration when comparing that to package declaration in Java?
No semicolon.

122. What's the difference between const and readonly?


You can initialize readonly variables to some runtime values. Let's say your program uses current date and time as one of the values that won't
change. This way you declare public readonly string DateT = new DateTime().ToString().

123. What happens when you encounter a continue statement inside the for loop? The code for the rest of the loop is ignored, the control is
transferred back to the beginning of the loop.
124. What's the advantage of using System.Text.StringBuilder over System.String? StringBuilder is more efficient in the cases, where a lot of
manipulation is done to the text. Strings are immutable, so each time it's being operated on, a new instance is created.

125. Can you store multiple data types in System.Array?


No.

126. What's the difference between the System.Array.CopyTo() and System.Array.Clone()? The first one performs a deep copy of the array, the
second one is shallow.

127. How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.

128. What's the .NET datatype that allows the retrieval of data by a unique key?
HashTable.

129. What's class SortedList underneath?


A sorted HashTable.

130. Will finally block get executed if the exception had not occurred?
Yes.

dot net questions(4)


• Can you explain what inheritance is and an example of when you might use it? Inheritance is a fundamental feature of an object oriented system
and it is simply the ability to inherit data and functionality from a parent object. Rather than developing new objects from scratch, new code can
be based on the work of other programmers, adding only new features that are needed.
• How would you implement inheritance using VB.NET/C#? When we set out to implement a class using inheritance, we must first start with an
existing class from which we will derive our new subclass. This existing class, or base class, may be part of the .NET system class library
framework, it may be part of some other application or .NET assembly, or we may create it as part of our existing application. Once we have a
base class, we can then implement one or more subclasses based on that base class. Each of our subclasses will automatically have all of the
methods, properties, and events of that base class ? including the implementation behind each method, property, and event. Our subclass can add
new methods, properties, and events of its own - extending the original interface with new functionality. Additionally, a subclass can replace the
methods and properties of the base class with its own new implementation - effectively overriding the original behavior and replacing it with new
behaviors. Essentially inheritance is a way of merging functionality from an existing class into our new subclass. Inheritance also defines rules
for how these methods, properties, and events can be merged.

dot net questions(5)


01. Does C# support multiple-inheritance?
Ans : No.

02. Who is a protected class-level variable available to?


Ans : It is available to any sub-class (a class inheriting this class).

03. Are private class-level variables inherited?


Ans : Yes, but they are not accessible. Although they are not visible or accessible via the class interface, they are inherited.

04. Describe the accessibility modifier “protected internal”.


Ans : It is available to classes that are within the same assembly and derived from the specified base class.

05. What’s the top .NET class that everything is derived from?
Ans : System.Object.

06. What does the term immutable mean?


Ans : The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a
new data value was created in memory.

07. What’s the difference between System.String and System.Text.StringBuilder classes?


Ans : System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations
can be performed.

08. What’s the advantage of using System.Text.StringBuilder over System.String?


Ans : StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string is
changed, a new instance in memory is created.
09. Can you store multiple data types in System.Array?
Ans : No.

10. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?


Ans : The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method
copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains
references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new
instance of each element's object, resulting in a different, yet identacle object.

dot net faq - part 1

1. Introduction

1.1 What is .NET?

.NET is a general-purpose software development platform, similar to Java. At its core is a virtual machine that turns intermediate language (IL)
into machine code. High-level language compilers for C#, VB.NET and C++ are provided to turn source code into IL. C# is a new programming
language, very similar to Java. An extensive class library is included, featuring all the functionality one might expect from a contempory
development platform - windows GUI development (Windows Forms), database access (ADO.NET), web development (ASP.NET), web
services, XML etc.

See also Microsoft's definition.

1.2 When was .NET announced?

Bill Gates delivered a keynote at Forum 2000, held June 22, 2000, outlining the .NET 'vision'. The July 2000 PDC had a number of sessions
on .NET technology, and delegates were given CDs containing a pre-release version of the .NET framework/SDK and Visual Studio.NET.

1.3 What versions of .NET are there?

The final versions of the 1.0 SDK and runtime were made publicly available around 6pm PST on 15-Jan-2002. At the same time, the final version
of Visual Studio.NET was made available to MSDN subscribers.

.NET 1.1 was released in April 2003, and was mostly bug fixes for 1.0.

.NET 2.0 was released to MSDN subscribers in late October 2005, and was officially launched in early November.

1.4 What operating systems does the .NET Framework run on?

The runtime supports Windows Server 2003, Windows XP, Windows 2000, NT4 SP6a and Windows ME/98. Windows 95 is not supported.
Some parts of the framework do not work on all platforms - for example, ASP.NET is only supported on XP and Windows 2000/2003. Windows
98/ME cannot be used for development.

IIS is not supported on Windows XP Home Edition, and so cannot be used to host ASP.NET. However, the ASP.NET Web Matrix web server
does run on XP Home.

The .NET Compact Framework is a version of the .NET Framework for mobile devices, running Windows CE or Windows Mobile.

The Mono project has a version of the .NET Framework that runs on Linux.

1.5 What tools can I use to develop .NET applications?

There are a number of tools, described here in ascending order of cost:


The .NET Framework SDK is free and includes command-line compilers for C++, C#, and VB.NET and various other utilities to aid
development.
SharpDevelop is a free IDE for C# and VB.NET.
Microsoft Visual Studio Express editions are cut-down versions of Visual Studio, for hobbyist or novice developers.There are different versions
for C#, VB, web development etc. Originally the plan was to charge $49, but MS has decided to offer them as free downloads instead, at least
until November 2006.
Microsoft Visual Studio Standard 2005 is around $300, or $200 for the upgrade.
Microsoft VIsual Studio Professional 2005 is around $800, or $550 for the upgrade.
At the top end of the price range are the Microsoft Visual Studio Team Edition for Software Developers 2005 with MSDN Premium and Team
Suite editions.

You can see the differences between the various Visual Studio versions here.

1.6 Why did they call it .NET?

I don't know what they were thinking. They certainly weren't thinking of people using search tools. It's meaningless marketing nonsense.

dot net faq - part 2

2. Terminology

2.1 What is the CLI? Is it the same as the CLR?

The CLI (Common Language Infrastructure) is the definiton of the fundamentals of the .NET framework - the Common Type System (CTS),
metadata, the Virtual Execution Environment (VES) and its use of intermediate language (IL), and the support of multiple programming
languages via the Common Language Specification (CLS). The CLI is documented through ECMA - see http://msdn.microsoft.com/net/ecma/ for
more details.

The CLR (Common Language Runtime) is Microsoft's primary implementation of the CLI. Microsoft also have a shared source implementation
known as ROTOR, for educational purposes, as well as the .NET Compact Framework for mobile devices. Non-Microsoft CLI implementations
include Mono and DotGNU Portable.NET.
2.2 What is the CTS, and how does it relate to the CLS?

CTS = Common Type System. This is the full range of types that the .NET runtime understands. Not all .NET languages support all the types in
the CTS.

CLS = Common Language Specification. This is a subset of the CTS which all .NET languages are expected to support. The idea is that any
program which uses CLS-compliant types can interoperate with any .NET program written in any language. This interop is very fine-grained - for
example a VB.NET class can inherit from a C# class.
2.3 What is IL?

IL = Intermediate Language. Also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language). All .NET
source code (of any language) is compiled to IL during development. The IL is then converted to machine code at the point where the software is
installed, or (more commonly) at run-time by a Just-In-Time (JIT) compiler.
2.4 What is C#?

C# is a new language designed by Microsoft to work with the .NET framework. In their "Introduction to C#" whitepaper, Microsoft describe C#
as follows:

"C# is a simple, modern, object oriented, and type-safe programming language derived from C and C++. C# (pronounced “C sharp”) is firmly
planted in the C and C++ family tree of languages, and will immediately be familiar to C and C++ programmers. C# aims to combine the high
productivity of Visual Basic and the raw power of C++."

Substitute 'Java' for 'C#' in the quote above, and you'll see that the statement still works pretty well :-).

If you are a C++ programmer, you might like to check out my C# FAQ.
2.5 What does 'managed' mean in the .NET context?

The term 'managed' is the cause of much confusion. It is used in various places within .NET, meaning slightly different things.

Managed code: The .NET framework provides several core run-time services to the programs that run within it - for example exception handling
and security. For these services to work, the code must provide a minimum level of information to the runtime. Such code is called managed
code.

Managed data: This is data that is allocated and freed by the .NET runtime's garbage collector.

Managed classes: This is usually referred to in the context of Managed Extensions (ME) for C++. When using ME C++, a class can be marked
with the __gc keyword. As the name suggests, this means that the memory for instances of the class is managed by the garbage collector, but it
also means more than that. The class becomes a fully paid-up member of the .NET community with the benefits and restrictions that brings. An
example of a benefit is proper interop with classes written in other languages - for example, a managed C++ class can inherit from a VB class. An
example of a restriction is that a managed class can only inherit from one base class.
2.6 What is reflection?

All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is packaged along with the module
(modules in turn are packaged together in assemblies), and can be accessed by a mechanism called reflection. The System.Reflection namespace
contains classes that can be used to interrogate the types for a module/assembly.

Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfo to access type library data in COM, and it is used for
similar purposes - e.g. determining data type sizes for marshaling data across context/process/machine boundaries.

Reflection can also be used to dynamically invoke methods (see System.Type.InvokeMember), or even create types dynamically at run-time (see
System.Reflection.Emit.TypeBuilder).

dot net faq - part 3

. Assemblies

3.1 What is an assembly?

An assembly is sometimes described as a logical .EXE or .DLL, and can be an application (with a main entry point) or a library. An assembly
consists of one or more files (dlls, exes, html files etc), and represents a group of resources, type definitions, and implementations of those types.
An assembly may also contain references to other assemblies. These resources, types and references are described in a block of data called a
manifest. The manifest is part of the assembly, thus making the assembly self-describing.

An important aspect of assemblies is that they are part of the identity of a type. The identity of a type is the assembly that houses it combined
with the type name. This means, for example, that if assembly A exports a type called T, and assembly B exports a type called T, the .NET
runtime sees these as two completely different types. Furthermore, don't get confused between assemblies and namespaces - namespaces are
merely a hierarchical way of organising type names. To the runtime, type names are type names, regardless of whether namespaces are used to
organise the names. It's the assembly plus the typename (regardless of whether the type name belongs to a namespace) that uniquely indentifies a
type to the runtime.

Assemblies are also important in .NET with respect to security - many of the security restrictions are enforced at the assembly boundary.

Finally, assemblies are the unit of versioning in .NET - more on this below.
3.2 How can I produce an assembly?

The simplest way to produce an assembly is directly from a .NET compiler. For example, the following C# program:
public class CTest
{
public CTest() { System.Console.WriteLine( "Hello from CTest" ); }
}

can be compiled into a library assembly (dll) like this:


csc /t:library ctest.cs

You can then view the contents of the assembly by running the "IL Disassembler" tool that comes with the .NET SDK.

Alternatively you can compile your source into modules, and then combine the modules into an assembly using the assembly linker (al.exe). For
the C# compiler, the /target:module switch is used to generate a module instead of an assembly.
3.3 What is the difference between a private assembly and a shared assembly?

Location and visibility: 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 assembly is normally stored in the global assembly cache, which is a repository of assemblies maintained by the .NET runtime.
Shared assemblies are usually libraries of code which many applications will find useful, e.g. the .NET framework classes.
Versioning: The runtime enforces versioning constraints only on shared assemblies, not on private assemblies.

3.4 How do assemblies find each other?

By searching directory paths. There are several factors which can affect the path (such as the AppDomain host, and application configuration
files), but for private assemblies the search path is normally the application's directory and its sub-directories. For shared assemblies, the search
path is normally same as the private assembly path plus the shared assembly cache.
3.5 How does assembly versioning work?

Each assembly has a version number called the compatibility version. Also each reference to an assembly (from another assembly) includes both
the name and version of the referenced assembly.

The version number has four numeric parts (e.g. 5.5.2.33). Assemblies with either of the first two parts different are normally viewed as
incompatible. If the first two parts are the same, but the third is different, the assemblies are deemed as 'maybe compatible'. If only the fourth part
is different, the assemblies are deemed compatible. However, this is just the default guideline - it is the version policy that decides to what extent
these rules are enforced. The version policy can be specified via the application configuration file.

Remember: versioning is only applied to shared assemblies, not private assemblies.


3.6 How can I develop an application that automatically updates itself from the web?

For .NET 1.x, use the Updater Application Block. For .NET 2.x, use ClickOnce.

dot net faq -- part 4

4. Application Domains

4.1 What is an application domain?

An AppDomain can be thought of as a lightweight process. Multiple AppDomains can exist inside a Win32 process. The primary purpose of the
AppDomain is to isolate applications from each other, and so it is particularly useful in hosting scenarios such as ASP.NET. An AppDomain can
be destroyed by the host without affecting other AppDomains in the process.

Win32 processes provide isolation by having distinct memory address spaces. This is effective, but expensive. The .NET runtime enforces
AppDomain isolation by keeping control over the use of memory - all memory in the AppDomain is managed by the .NET runtime, so the
runtime can ensure that AppDomains do not access each other's memory.

One non-obvious use of AppDomains is for unloading types. Currently the only way to unload a .NET type is to destroy the AppDomain it is
loaded into. This is particularly useful if you create and destroy types on-the-fly via reflection.

Microsoft have an AppDomain FAQ.


4.2 How does an AppDomain get created?

AppDomains are usually created by hosts. Examples of hosts are the Windows Shell, ASP.NET and IE. When you run a .NET application from
the command-line, the host is the Shell. The Shell creates a new AppDomain for every application.

AppDomains can also be explicitly created by .NET applications. Here is a C# sample which creates an AppDomain, creates an instance of an
object inside it, and then executes one of the object's methods:
using System;
using System.Runtime.Remoting;
using System.Reflection;

public class CAppDomainInfo : MarshalByRefObject


{
public string GetName() { return AppDomain.CurrentDomain.FriendlyName; }
}

public class App


{
public static int Main()
{
AppDomain ad = AppDomain.CreateDomain( "Andy's new domain" );
CAppDomainInfo adInfo = (CAppDomainInfo)ad.CreateInstanceAndUnwrap(
Assembly.GetCallingAssembly().GetName().Name, "CAppDomainInfo" );
Console.WriteLine( "Created AppDomain name = " + adInfo.GetName() );
return 0;
}
}

4.3 Can I write my own .NET host?

Yes. For an example of how to do this, take a look at the source for the dm.net moniker developed by Jason Whittington and Don Box. There is
also a code sample in the .NET SDK called CorHost.

dot net -faq - part 5


5. Garbage Collection

5.1 What is garbage collection?

Garbage collection is a heap-management strategy where a run-time component takes responsibility for managing the lifetime of the memory
used by objects. This concept is not new to .NET - Java and many other languages/runtimes have used garbage collection for some time.
5.2 Is it true that objects don't always get destroyed immediately when the last reference goes away?

Yes. The garbage collector offers no guarantees about the time when an object will be destroyed and its memory reclaimed.

There was an interesting thread on the DOTNET list, started by Chris Sells, about the implications of non-deterministic destruction of objects in
C#. In October 2000, Microsoft's Brian Harry posted a lengthy analysis of the problem. Chris Sells' response to Brian's posting is here.
5.3 Why doesn't the .NET runtime offer deterministic destruction?

Because of the garbage collection algorithm. The .NET garbage collector works by periodically running through a list of all the objects that are
currently being referenced by an application. All the objects that it doesn't find during this search are ready to be destroyed and the memory
reclaimed. The implication of this algorithm is that the runtime doesn't get notified immediately when the final reference on an object goes away
- it only finds out during the next 'sweep' of the heap.

Futhermore, this type of algorithm works best by performing the garbage collection sweep as rarely as possible. Normally heap exhaustion is the
trigger for a collection sweep.
5.4 Is the lack of deterministic destruction in .NET a problem?

It's certainly an issue that affects component design. If you have objects that maintain expensive or scarce resources (e.g. database locks), you
need to provide some way to tell the object to release the resource when it is done. Microsoft recommend that you provide a method called
Dispose() for this purpose. However, this causes problems for distributed objects - in a distributed system who calls the Dispose() method? Some
form of reference-counting or ownership-management mechanism is needed to handle distributed objects - unfortunately the runtime offers no
help with this.
5.5 Should I implement Finalize on my class? Should I implement IDisposable?

This issue is a little more complex than it first appears. There are really two categories of class that require deterministic destruction - the first
category manipulate unmanaged types directly, whereas the second category manipulate managed types that require deterministic destruction. An
example of the first category is a class with an IntPtr member representing an OS file handle. An example of the second category is a class with a
System.IO.FileStream member.

For the first category, it makes sense to implement IDisposable and override Finalize. This allows the object user to 'do the right thing' by calling
Dispose, but also provides a fallback of freeing the unmanaged resource in the Finalizer, should the calling code fail in its duty. However this
logic does not apply to the second category of class, with only managed resources. In this case implementing Finalize is pointless, as managed
member objects cannot be accessed in the Finalizer. This is because there is no guarantee about the ordering of Finalizer execution. So only the
Dispose method should be implemented. (If you think about it, it doesn't really make sense to call Dispose on member objects from a Finalizer
anyway, as the member object's Finalizer will do the required cleanup.)

For classes that need to implement IDisposable and override Finalize, see Microsoft's documented pattern.

Note that some developers argue that implementing a Finalizer is always a bad idea, as it hides a bug in your code (i.e. the lack of a Dispose call).
A less radical approach is to implement Finalize but include a Debug.Assert at the start, thus signalling the problem in developer builds but
allowing the cleanup to occur in release builds.
5.6 Do I have any control over the garbage collection algorithm?

A little. For example the System.GC class exposes a Collect method, which forces the garbage collector to collect all unreferenced objects
immediately.

Also there is a gcConcurrent setting that can be specified via the application configuration file. This specifies whether or not the garbage collector
performs some of its collection activities on a separate thread. The setting only applies on multi-processor machines, and defaults to true.
5.7 How can I find out what the garbage collector is doing?

Lots of interesting statistics are exported from the .NET runtime via the '.NET CLR xxx' performance counters. Use Performance Monitor to
view them.
5.8 What is the lapsed listener problem?

The lapsed listener problem is one of the primary causes of leaks in .NET applications. It occurs when a subscriber (or 'listener') signs up for a
publisher's event, but fails to unsubscribe. The failure to unsubscribe means that the publisher maintains a reference to the subscriber as long as
the publisher is alive. For some publishers, this may be the duration of the application.

This situation causes two problems. The obvious problem is the leakage of the subscriber object. The other problem is the performance
degredation due to the publisher sending redundant notifications to 'zombie' subscribers.
There are at least a couple of solutions to the problem. The simplest is to make sure the subscriber is unsubscribed from the publisher, typically
by adding an Unsubscribe() method to the subscriber. Another solution, documented here by Shawn Van Ness, is to change the publisher to use
weak references in its subscriber list.
5.9 When do I need to use GC.KeepAlive?

It's very unintuitive, but the runtime can decide that an object is garbage much sooner than you expect. More specifically, an object can become
garbage while a method is executing on the object, which is contrary to most developers' expectations. Chris Brumme explains the issue on his
blog. I've taken Chris's code and expanded it into a full app that you can play with if you want to prove to yourself that this is a real problem:
using System;
using System.Runtime.InteropServices;

class Win32
{
[DllImport("kernel32.dll")]
public static extern IntPtr CreateEvent( IntPtr lpEventAttributes,
bool bManualReset,bool bInitialState, string lpName);

[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool CloseHandle(IntPtr hObject);

[DllImport("kernel32.dll")]
public static extern bool SetEvent(IntPtr hEvent);
}

class EventUser
{
public EventUser()
{
hEvent = Win32.CreateEvent( IntPtr.Zero, false, false, null );
}

~EventUser()
{
Win32.CloseHandle( hEvent );
Console.WriteLine("EventUser finalized");
}

public void UseEvent()


{
UseEventInStatic( this.hEvent );
}

static void UseEventInStatic( IntPtr hEvent )


{
//GC.Collect();
bool bSuccess = Win32.SetEvent( hEvent );
Console.WriteLine( "SetEvent " + (bSuccess ? "succeeded" : "FAILED!") );
}

IntPtr hEvent;
}

class App
{
static void Main(string[] args)
{
EventUser eventUser = new EventUser();
eventUser.UseEvent();
}
}

If you run this code, it'll probably work fine, and you'll get the following output:
SetEvent succeeded
EventDemo finalized

However, if you uncomment the GC.Collect() call in the UseEventInStatic() method, you'll get this output:
EventDemo finalized
SetEvent FAILED!

(Note that you need to use a release build to reproduce this problem.)

So what's happening here? Well, at the point where UseEvent() calls UseEventInStatic(), a copy is taken of the hEvent field, and there are no
further references to the EventUser object anywhere in the code. So as far as the runtime is concerned, the EventUser object is garbage and can
be collected. Normally of course the collection won't happen immediately, so you'll get away with it, but sooner or later a collection will occur at
the wrong time, and your app will fail.

A solution to this problem is to add a call to GC.KeepAlive(this) to the end of the UseEvent method, as Chris explains.

dot net faq - part 6

6. Serialization

6.1 What is serialization?

Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite process, i.e. creating an object from a
stream of bytes. Serialization/Deserialization is mostly used to transport objects (e.g. during remoting), or to persist objects (e.g. to a file or
database).
6.2 Does the .NET Framework have in-built support for serialization?

There are two separate mechanisms provided by the .NET class library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses
XmlSerializer for Web Services, and SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.
6.3 I want to serialize instances of my class. Should I use XmlSerializer, SoapFormatter or BinaryFormatter?

It depends. XmlSerializer has severe limitations such as the requirement that the target class has a parameterless constructor, and only public
read/write properties and fields can be serialized. However, on the plus side, XmlSerializer has good support for customising the XML document
that is produced or consumed. XmlSerializer's features mean that it is most suitable for cross-platform work, or for constructing objects from
existing XML documents.

SoapFormatter and BinaryFormatter have fewer limitations than XmlSerializer. They can serialize private fields, for example. However they both
require that the target class be marked with the [Serializable] attribute, so like XmlSerializer the class needs to be written with serialization in
mind. Also there are some quirks to watch out for - for example on deserialization the constructor of the new object is not invoked.

The choice between SoapFormatter and BinaryFormatter depends on the application. BinaryFormatter makes sense where both serialization and
deserialization will be performed on the .NET platform and where performance is important. SoapFormatter generally makes more sense in all
other cases, for ease of debugging if nothing else.
6.4 Can I customise the serialization process?

Yes. XmlSerializer supports a range of attributes that can be used to configure serialization for a particular class. For example, a field or property
can be marked with the [XmlIgnore] attribute to exclude it from serialization. Another example is the [XmlElement] attribute, which can be used
to specify the XML element name to be used for a particular property or field.

Serialization via SoapFormatter/BinaryFormatter can also be controlled to some extent by attributes. For example, the [NonSerialized] attribute is
the equivalent of XmlSerializer's [XmlIgnore] attribute. Ultimate control of the serialization process can be acheived by implementing the the
ISerializable interface on the class whose instances are to be serialized.
6.5 Why is XmlSerializer so slow?

There is a once-per-process-per-type overhead with XmlSerializer. So the first time you serialize or deserialize an object of a given type in an
application, there is a significant delay. This normally doesn't matter, but it may mean, for example, that XmlSerializer is a poor choice for
loading configuration settings during startup of a GUI application.
6.6 Why do I get errors when I try to serialize a Hashtable?

XmlSerializer will refuse to serialize instances of any class that implements IDictionary, e.g. Hashtable. SoapFormatter and BinaryFormatter do
not have this restriction.
6.7 XmlSerializer is throwing a generic "There was an error reflecting MyClass" error. How do I find out what the problem is?

Look at the InnerException property of the exception that is thrown to get a more specific error message.
6.8 Why am I getting an InvalidOperationException when I serialize an ArrayList?

XmlSerializer needs to know in advance what type of objects it will find in an ArrayList. To specify the type, use the XmlArrayItem attibute like
this:
public class Person
{
public string Name;
public int Age;
}

public class Population


{
[XmlArrayItem(typeof(Person))] public ArrayList People;
}

dot net faq - part 7

7. Attributes

7.1 What are attributes?

There are at least two types of .NET attribute. The first type I will refer to as a metadata attribute - it allows some data to be attached to a class or
method. This data becomes part of the metadata for the class, and (like other class metadata) can be accessed via reflection. An example of a
metadata attribute is [serializable], which can be attached to a class and means that instances of the class can be serialized.
[serializable] public class CTest {}

The other type of attribute is a context attribute. Context attributes use a similar syntax to metadata attributes but they are fundamentally
different. Context attributes provide an interception mechanism whereby instance activation and method calls can be pre- and/or post-processed.
If you have encountered Keith Brown's universal delegator you'll be familiar with this idea.
7.2 Can I create my own metadata attributes?

Yes. Simply derive a class from System.Attribute and mark it with the AttributeUsage attribute. For example:
[AttributeUsage(AttributeTargets.Class)]
public class InspiredByAttribute : System.Attribute
{
public string InspiredBy;

public InspiredByAttribute( string inspiredBy )


{
InspiredBy = inspiredBy;
}
}

[InspiredBy("Andy Mc's brilliant .NET FAQ")]


class CTest
{
}

class CApp
{
public static void Main()
{
object[] atts = typeof(CTest).GetCustomAttributes(true);

foreach( object att in atts )


if( att is InspiredByAttribute )
Console.WriteLine( "Class CTest was inspired by {0}", ((InspiredByAttribute)att).InspiredBy );
}
}

7.3 Can I create my own context attibutes?

Yes. Take a look at Peter Drayton's Tracehook.NET.


8. Code Access Security

8.1 What is Code Access Security (CAS)?


CAS is the part of the .NET security model that determines whether or not code is allowed to run, and what resources it can use when it is
running. For example, it is CAS that will prevent a .NET web applet from formatting your hard disk.
8.2 How does CAS work?

The CAS security policy revolves around two key concepts - code groups and permissions. Each .NET assembly is a member of a particular code
group, and each code group is granted the permissions specified in a named permission set.

For example, using the default security policy, a control downloaded from a web site belongs to the 'Zone - Internet' code group, which adheres
to the permissions defined by the 'Internet' named permission set. (Naturally the 'Internet' named permission set represents a very restrictive range
of permissions.)
8.3 Who defines the CAS code groups?

Microsoft defines some default ones, but you can modify these and even create your own. To see the code groups defined on your system, run
'caspol -lg' from the command-line. On my system it looks like this:
Level = Machine

Code Groups:

1. All code: Nothing


1.1. Zone - MyComputer: FullTrust
1.1.1. Honor SkipVerification requests: SkipVerification
1.2. Zone - Intranet: LocalIntranet
1.3. Zone - Internet: Internet
1.4. Zone - Untrusted: Nothing
1.5. Zone - Trusted: Internet
1.6. StrongName -
0024000004800000940000000602000000240000525341310004000003
000000CFCB3291AA715FE99D40D49040336F9056D7886FED46775BC7BB5430BA4444FEF8348EBD06
F962F39776AE4DC3B7B04A7FE6F49F25F740423EBF2C0B89698D8D08AC48D69CED0FC8F83B465E08
07AC11EC1DCC7D054E807A43336DDE408A5393A48556123272CEEEE72F1660B71927D38561AABF5C
AC1DF1734633C602F8F2D5: Everything

Note the hierarchy of code groups - the top of the hierarchy is the most general ('All code'), which is then sub-divided into several groups, each of
which in turn can be sub-divided. Also note that (somewhat counter-intuitively) a sub-group can be associated with a more permissive permission
set than its parent.
8.4 How do I define my own code group?

Use caspol. For example, suppose you trust code from www.mydomain.com and you want it have full access to your system, but you want to
keep the default restrictions for all other internet sites. To achieve this, you would add a new code group as a sub-group of the 'Zone - Internet'
group, like this:
caspol -ag 1.3 -site www.mydomain.com FullTrust

Now if you run caspol -lg you will see that the new group has been added as group 1.3.1:
...
1.3. Zone - Internet: Internet
1.3.1. Site - www.mydomain.com: FullTrust
...

Note that the numeric label (1.3.1) is just a caspol invention to make the code groups easy to manipulate from the command-line. The underlying
runtime never sees it.
8.5 How do I change the permission set for a code group?

Use caspol. If you are the machine administrator, you can operate at the 'machine' level - which means not only that the changes you make
become the default for the machine, but also that users cannot change the permissions to be more permissive. If you are a normal (non-admin)
user you can still modify the permissions, but only to make them more restrictive. For example, to allow intranet code to do what it likes you
might do this:
caspol -cg 1.2 FullTrust

Note that because this is more permissive than the default policy (on a standard system), you should only do this at the machine level - doing it at
the user level will have no effect.
8.6 Can I create my own permission set?

Yes. Use caspol -ap, specifying an XML file containing the permissions in the permission set. To save you some time, here is a sample file
corresponding to the 'Everything' permission set - just edit to suit your needs. When you have edited the sample, add it to the range of available
permission sets like this:
caspol -ap samplepermset.xml

Then, to apply the permission set to a code group, do something like this:
caspol -cg 1.3 SamplePermSet

(By default, 1.3 is the 'Internet' code group)


8.7 I'm having some trouble with CAS. How can I troubleshoot the problem?

Caspol has a couple of options that might help. First, you can ask caspol to tell you what code group an assembly belongs to, using caspol -rsg.
Similarly, you can ask what permissions are being applied to a particular assembly using caspol -rsp.
8.8 I can't be bothered with CAS. Can I turn it off?

Yes, as long as you are an administrator. Just run:


caspol -s off

dot net faq part 8

9. Intermediate Language (IL)

9.1 Can I look at the IL for an assembly?

Yes. MS supply a tool called Ildasm that can be used to view the metadata and IL for an assembly.
9.2 Can source code be reverse-engineered from IL?

Yes, it is often relatively straightforward to regenerate high-level source from IL. Lutz Roeder's Reflector does a very good job of turning IL into
C# or VB.NET.
9.3 How can I stop my code being reverse-engineered from IL?

You can buy an IL obfuscation tool. These tools work by 'optimising' the IL in such a way that reverse-engineering becomes much more difficult.

Of course if you are writing web services then reverse-engineering is not a problem as clients do not have access to your IL.
9.4 Can I write IL programs directly?

Yes. Peter Drayton posted this simple example to the DOTNET mailing list:
.assembly MyAssembly {}
.class MyApp {
.method static void Main() {
.entrypoint
ldstr "Hello, IL!"
call void System.Console::WriteLine(class System.Object)
ret
}
}

Just put this into a file called hello.il, and then run ilasm hello.il. An exe assembly will be generated.
9.5 Can I do things in IL that I can't do in C#?

Yes. A couple of simple examples are that you can throw exceptions that are not derived from System.Exception, and you can have non-zero-
based arrays.
10. Implications for COM

10.1 Does .NET replace COM?

This subject causes a lot of controversy, as you'll see if you read the mailing list archives. Take a look at the following two threads:

http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&D=0&P=68241
http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P=R60761

The bottom line is that .NET has its own mechanisms for type interaction, and they don't use COM. No IUnknown, no IDL, no typelibs, no
registry-based activation. This is mostly good, as a lot of COM was ugly. Generally speaking, .NET allows you to package and use components
in a similar way to COM, but makes the whole thing a bit easier.
10.2 Is DCOM dead?

Pretty much, for .NET developers. The .NET Framework has a new remoting model which is not based on DCOM. DCOM was pretty much dead
anyway, once firewalls became widespread and Microsoft got SOAP fever. Of course DCOM will still be used in interop scenarios.
10.3 Is COM+ dead?

Not immediately. The approach for .NET 1.0 was to provide access to the existing COM+ services (through an interop layer) rather than replace
the services with native .NET ones. Various tools and attributes were provided to make this as painless as possible. Over time it is expected that
interop will become more seamless - this may mean that some services become a core part of the CLR, and/or it may mean that some services
will be rewritten as managed code which runs on top of the CLR.

For more on this topic, search for postings by Joe Long in the archives - Joe is the MS group manager for COM+. Start with this message:

http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P=R68370
10.4 Can I use COM components from .NET programs?

Yes. COM components are accessed from the .NET runtime via a Runtime Callable Wrapper (RCW). This wrapper turns the COM interfaces
exposed by the COM component into .NET-compatible interfaces. For oleautomation interfaces, the RCW can be generated automatically from a
type library. For non-oleautomation interfaces, it may be necessary to develop a custom RCW which manually maps the types exposed by the
COM interface to .NET-compatible types.

Here's a simple example for those familiar with ATL. First, create an ATL component which implements the following IDL:
import "oaidl.idl";
import "ocidl.idl";

[
object,
uuid(EA013F93-487A-4403-86EC-FD9FEE5E6206),
helpstring("ICppName Interface"),
pointer_default(unique),
oleautomation
]

interface ICppName : IUnknown


{
[helpstring("method SetName")] HRESULT SetName([in] BSTR name);
[helpstring("method GetName")] HRESULT GetName([out,retval] BSTR *pName );
};

[
uuid(F5E4C61D-D93A-4295-A4B4-2453D4A4484D),
version(1.0),
helpstring("cppcomserver 1.0 Type Library")
]
library CPPCOMSERVERLib
{
importlib("stdole32.tlb");
importlib("stdole2.tlb");
[
uuid(600CE6D9-5ED7-4B4D-BB49-E8D5D5096F70),
helpstring("CppName Class")
]
coclass CppName
{
[default] interface ICppName;
};
};

When you've built the component, you should get a typelibrary. Run the TLBIMP utility on the typelibary, like this:
tlbimp cppcomserver.tlb

If successful, you will get a message like this:


Typelib imported successfully to CPPCOMSERVERLib.dll

You now need a .NET client - let's use C#. Create a .cs file containing the following code:
using System;
using CPPCOMSERVERLib;

public class MainApp


{
static public void Main()
{
CppName cppname = new CppName();
cppname.SetName( "bob" );
Console.WriteLine( "Name is " + cppname.GetName() );
}
}

Compile the C# code like this:


csc /r:cppcomserverlib.dll csharpcomclient.cs

Note that the compiler is being told to reference the DLL we previously generated from the typelibrary using TLBIMP. You should now be able
to run csharpcomclient.exe, and get the following output on the console:
Name is bob

10.5 Can I use .NET components from COM programs?

Yes. .NET components are accessed from COM via a COM Callable Wrapper (CCW). This is similar to a RCW (see previous question), but
works in the opposite direction. Again, if the wrapper cannot be automatically generated by the .NET development tools, or if the automatic
behaviour is not desirable, a custom CCW can be developed. Also, for COM to 'see' the .NET component, the .NET component must be
registered in the registry.

Here's a simple example. Create a C# file called testcomserver.cs and put the following in it:
using System;
using System.Runtime.InteropServices;

namespace AndyMc
{
[ClassInterface(ClassInterfaceType.AutoDual)]
public class CSharpCOMServer
{
public CSharpCOMServer() {}
public void SetName( string name ) { m_name = name; }
public string GetName() { return m_name; }
private string m_name;
}
}

Then compile the .cs file as follows:


csc /target:library testcomserver.cs

You should get a dll, which you register like this:


regasm testcomserver.dll /tlb:testcomserver.tlb /codebase

Now you need to create a client to test your .NET COM component. VBScript will do - put the following in a file called comclient.vbs:
Dim dotNetObj
Set dotNetObj = CreateObject("AndyMc.CSharpCOMServer")
dotNetObj.SetName ("bob")
MsgBox "Name is " & dotNetObj.GetName()

and run the script like this:


wscript comclient.vbs

And hey presto you should get a message box displayed with the text "Name is bob".

An alternative to the approach above it to use the dm.net moniker developed by Jason Whittington and Don Box.
10.6 Is ATL redundant in the .NET world?

Yes. ATL will continue to be valuable for writing COM components for some time, but it has no place in the .NET world.

dot net faq part 9

11. Threads

11.1 How do I spawn a thread?

Create an instance of a System.Threading.Thread object, passing it an instance of a ThreadStart delegate that will be executed on the new thread.
For example:
class MyThread
{
public MyThread( string initData )
{
m_data = initData;
m_thread = new Thread( new ThreadStart(ThreadMain) );
m_thread.Start();
}

// ThreadMain() is executed on the new thread.


private void ThreadMain()
{
Console.WriteLine( m_data );
}

public void WaitUntilFinished()


{
m_thread.Join();
}

private Thread m_thread;


private string m_data;
}

In this case creating an instance of the MyThread class is sufficient to spawn the thread and execute the MyThread.ThreadMain() method:
MyThread t = new MyThread( "Hello, world." );
t.WaitUntilFinished();

11.2 How do I stop a thread?

There are several options. First, you can use your own communication mechanism to tell the ThreadStart method to finish. Alternatively the
Thread class has in-built support for instructing the thread to stop. The two principle methods are Thread.Interrupt() and Thread.Abort(). The
former will cause a ThreadInterruptedException to be thrown on the thread when it next goes into a WaitJoinSleep state. In other words,
Thread.Interrupt is a polite way of asking the thread to stop when it is no longer doing any useful work. In contrast, Thread.Abort() throws a
ThreadAbortException regardless of what the thread is doing. Furthermore, the ThreadAbortException cannot normally be caught (though the
ThreadStart's finally method will be executed). Thread.Abort() is a heavy-handed mechanism which should not normally be required.
11.3 How do I use the thread pool?

By passing an instance of a WaitCallback delegate to the ThreadPool.QueueUserWorkItem() method


class CApp
{
static void Main()
{
string s = "Hello, World";
ThreadPool.QueueUserWorkItem( new WaitCallback( DoWork ), s );

Thread.Sleep( 1000 ); // Give time for work item to be executed


}

// DoWork is executed on a thread from the thread pool.


static void DoWork( object state )
{
Console.WriteLine( state );
}
}

11.4 How do I know when my thread pool work item has completed?

There is no way to query the thread pool for this information. You must put code into the WaitCallback method to signal that it has completed.
Events are useful for this.
11.5 How do I prevent concurrent access to my data?

Each object has a concurrency lock (critical section) associated with it. The System.Threading.Monitor.Enter/Exit methods are used to acquire
and release this lock. For example, instances of the following class only allow one thread at a time to enter method f():
class C
{
public void f()
{
try
{
Monitor.Enter(this);
...
}
finally
{
Monitor.Exit(this);
}
}
}

C# has a 'lock' keyword which provides a convenient shorthand for the code above:
class C
{
public void f()
{
lock(this)
{
...
}
}
}

Note that calling Monitor.Enter(myObject) does NOT mean that all access to myObject is serialized. It means that the synchronisation lock
associated with myObject has been acquired, and no other thread can acquire that lock until Monitor.Exit(o) is called. In other words, this class is
functionally equivalent to the classes above:
class C
{
public void f()
{
lock( m_object )
{
...
}
}

private m_object = new object();


}

Actually, it could be argued that this version of the code is superior, as the lock is totally encapsulated within the class, and not accessible to the
user of the object.
11.6 Should I use ReaderWriterLock instead of Monitor.Enter/Exit?

Maybe, but be careful. ReaderWriterLock is used to allow multiple threads to read from a data source, while still granting exclusive access to a
single writer thread. This makes sense for data access that is mostly read-only, but there are some caveats. First, ReaderWriterLock is relatively
poor performing compared to Monitor.Enter/Exit, which offsets some of the benefits. Second, you need to be very sure that the data structures
you are accessing fully support multithreaded read access. Finally, there is apparently a bug in the v1.1 ReaderWriterLock that can cause
starvation for writers when there are a large number of readers.

Ian Griffiths has some interesting discussion on ReaderWriterLock here and here.

12. Tracing

12.1 Is there built-in support for tracing/logging?

Yes, in the System.Diagnostics namespace. There are two main classes that deal with tracing - Debug and Trace. They both work in a similar
way - the difference is that tracing from the Debug class only works in builds that have the DEBUG symbol defined, whereas tracing from the
Trace class only works in builds that have the TRACE symbol defined. Typically this means that you should use
System.Diagnostics.Trace.WriteLine for tracing that you want to work in debug and release builds, and System.Diagnostics.Debug.WriteLine for
tracing that you want to work only in debug builds.
12.2 Can I redirect tracing to a file?

Yes. The Debug and Trace classes both have a Listeners property, which is a collection of sinks that receive the tracing that you send via
Debug.WriteLine and Trace.WriteLine respectively. By default the Listeners collection contains a single sink, which is an instance of the
DefaultTraceListener class. This sends output to the Win32 OutputDebugString() function and also the System.Diagnostics.Debugger.Log()
method. This is useful when debugging, but if you're trying to trace a problem at a customer site, redirecting the output to a file is more
appropriate. Fortunately, the TextWriterTraceListener class is provided for this purpose.
Here's how to use the TextWriterTraceListener class to redirect Trace output to a file:
Trace.Listeners.Clear();
FileStream fs = new FileStream( @"c:\log.txt", FileMode.Create, FileAccess.Write );
Trace.Listeners.Add( new TextWriterTraceListener( fs ) );

Trace.WriteLine( @"This will be writen to c:\log.txt!" );


Trace.Flush();

Note the use of Trace.Listeners.Clear() to remove the default listener. If you don't do this, the output will go to the file and OutputDebugString().
Typically this is not what you want, because OutputDebugString() imposes a big performance hit.
12.3 Can I customise the trace output?

Yes. You can write your own TraceListener-derived class, and direct all output through it. Here's a simple example, which derives from
TextWriterTraceListener (and therefore has in-built support for writing to files, as shown above) and adds timing information and the thread ID
for each trace line:
class MyListener : TextWriterTraceListener
{
public MyListener( Stream s ) : base(s)
{
}

public override void WriteLine( string s )


{
Writer.WriteLine( "{0:D8} [{1:D4}] {2}",
Environment.TickCount - m_startTickCount,
AppDomain.GetCurrentThreadId(),
s );
}

protected int m_startTickCount = Environment.TickCount;


}

(Note that this implementation is not complete - the TraceListener.Write method is not overridden for example.)

The beauty of this approach is that when an instance of MyListener is added to the Trace.Listeners collection, all calls to Trace.WriteLine() go
through MyListener, including calls made by referenced assemblies that know nothing about the MyListener class.
12.4 Are there any third party logging components available?

Log4net is a port of the established log4j Java logging component.

dot net faq part 10

13.1 How does .NET remoting work?

.NET remoting involves sending messages along channels. Two of the standard channels are HTTP and TCP. TCP is intended for LANs only -
HTTP can be used for LANs or WANs (internet).

Support is provided for multiple message serializarion formats. Examples are SOAP (XML-based) and binary. By default, the HTTP channel
uses SOAP (via the .NET runtime Serialization SOAP Formatter), and the TCP channel uses binary (via the .NET runtime Serialization Binary
Formatter). But either channel can use either serialization format.

There are a number of styles of remote access:


SingleCall. Each incoming request from a client is serviced by a new object. The object is thrown away when the request has finished.
Singleton. All incoming requests from clients are processed by a single server object.
Client-activated object. This is the old stateful (D)COM model whereby the client receives a reference to the remote object and holds that
reference (thus keeping the remote object alive) until it is finished with it.

Distributed garbage collection of objects is managed by a system called 'leased based lifetime'. Each object has a lease time, and when that time
expires the object is disconnected from the .NET runtime remoting infrastructure. Objects have a default renew time - the lease is renewed when
a successful call is made from the client to the object. The client can also explicitly renew the lease.

If you're interested in using XML-RPC as an alternative to SOAP, take a look at Charles Cook's XML-RPC.Net.
13.2 How can I get at the Win32 API from a .NET program?
Use P/Invoke. This uses similar technology to COM Interop, but is used to access static DLL entry points instead of COM objects. Here is an
example of C# calling the Win32 MessageBox function:
using System;
using System.Runtime.InteropServices;

class MainApp
{
[DllImport("user32.dll", EntryPoint="MessageBox", SetLastError=true, CharSet=CharSet.Auto)]
public static extern int MessageBox(int hWnd, String strMessage, String strCaption, uint uiType);

public static void Main()


{
MessageBox( 0, "Hello, this is PInvoke in operation!", ".NET", 0 );
}
}

Pinvoke.net is a great resource for off-the-shelf P/Invoke signatures.


13.3 How do I write to the application configuration file at runtime?

You don't. See http://www.interact-sw.co.uk/iangblog/2004/11/25/savingconfig.


13.4 What is the difference between an event and a delegate?

An event is just a wrapper for a multicast delegate. Adding a public event to a class is almost the same as adding a public multicast delegate field.
In both cases, subscriber objects can register for notifications, and in both cases the publisher object can send notifications to the subscribers.
However, a public multicast delegate has the undesirable property that external objects can invoke the delegate, something we'd normally want to
restrict to the publisher. Hence events - an event adds public methods to the containing class to add and remove receivers, but does not make the
invocation mechanism public.

See this post by Julien Couvreur for more discussion.


13.5 What size is a .NET object?

Each instance of a reference type has two fields maintained by the runtime - a method table pointer and a sync block. These are 4 bytes each on a
32-bit system, making a total of 8 bytes per object overhead. Obviously the instance data for the type must be added to this to get the overall size
of the object. So, for example, instances of the following class are 12 bytes each:
class MyInt
{
...
private int x;
}

However, note that with the current implementation of the CLR there seems to be a minimum object size of 12 bytes, even for classes with no
data (e.g. System.Object).

Values types have no equivalent overhead.


13.6 Will my .NET app run on 64-bit Windows?

64-bit (x64) versions of Windows support both 32-bit and 64-bit processes, and corresponding 32-bit and 64-bit versions of .NET 2.0. (.NET 1.1
is 32-bit only).

.NET 1.x apps automatically run as 32-bit processes on 64-bit Windows.

.NET 2.0 apps can either run as 32-bit processes or as 64-bit processes. The OS decides which to use based on the PE header of the executable.
The flags in the PE header are controlled via the compiler /platform switch, which allows the target of the app to be specified as 'x86', 'x64' or
'any cpu'. Normally you specify 'any cpu', and your app will run as 32-bit on 32-bit Windows and 64-bit on 64-bit Windows. However if you
have some 32-bit native code in your app (loaded via COM interop, for example), you will need to specify 'x86', which will force 64-bit
Windows to load your app in a 32-bit process. You can also tweak the 32-bit flag in the PE header using the SDK corflags utility.

Some more explanation here:

http://blogs.msdn.com/gauravseth/archive/2006/03/07/545104.aspx
http://blogs.msdn.com/joshwil/archive/2005/04/08/406567.aspx
http://msdn.microsoft.com/netframework/programming/64bit/gettingstarted/
14. .NET 2.0

14.1 What are the new features of .NET 2.0?

Generics, anonymous methods, partial classes, iterators, property visibility (separate visibility for get and set) and static classes. See
http://msdn.microsoft.com/msdnmag/issues/04/05/C20/default.aspx for more information about these features.
14.2 What are the new 2.0 features useful for?

Generics are useful for writing efficient type-independent code, particularly where the types might include value types. The obvious application
is container classes, and the .NET 2.0 class library includes a suite of generic container classes in the System.Collections.Generic namespace.
Here's a simple example of a generic container class being used:
List myList = new List();
myList.Add( 10 );

Anonymous methods reduce the amount of code you have to write when using delegates, and are therefore especially useful for GUI
programming. Here's an example
AppDomain.CurrentDomain.ProcessExit += delegate { Console.WriteLine("Process ending ..."); };

Partial classes is a useful feature for separating machine-generated code from hand-written code in the same class, and will therefore be heavily
used by development tools such as Visual Studio.

Iterators reduce the amount of code you need to write to implement IEnumerable/IEnumerator. Here's some sample code:
static void Main()
{
RandomEnumerator re = new RandomEnumerator( 5 );
foreach( double r in re )
Console.WriteLine( r );
Console.Read();
}

class RandomEnumerator : IEnumerable


{
public RandomEnumerator(int size) { m_size = size; }

public IEnumerator GetEnumerator()


{
Random rand = new Random();
for( int i=0; i < m_size; i++ )
yield return rand.NextDouble();
}

int m_size = 0;
}

The use of 'yield return' is rather strange at first sight. It effectively synthethises an implementation of IEnumerator, something we had to do
manually in .NET 1.x.
14.3 What's the problem with .NET generics?

.NET generics work great for container classes. But what about other uses? Well, it turns out that .NET generics have a major limitation - they
require the type parameter to be constrained. For example, you cannot do this:
static class Disposer
{
public static void Dispose(T obj) { obj.Dispose(); }
}

The C# compiler will refuse to compile this code, as the type T has not been constrained, and therefore only supports the methods of
System.Object. Dispose is not a method on System.Object, so the compilation fails. To fix this code, we need to add a where clause, to reassure
the compiler that our type T does indeed have a Dispose method
static class Disposer where T : IDisposable
{
public static void Dispose(T obj) { obj.Dispose(); }
}

The problem is that the requirement for explicit contraints is very limiting. We can use constraints to say that T implements a particular interface,
but we can't dilute that to simply say that T implements a particular method. Contrast this with C++ templates (for example), where no constraint
at all is required - it is assumed (and verified at compile time) that if the code invokes the Dispose() method on a type, then the type will support
the method.

In fact, after writing generic code with interface constraints, we quickly see that we haven't gained much over non-generic interface-based
programming. For example, we can easily rewrite the Disposer class without generics:
static class Disposer
{
public static void Dispose( IDisposable obj ) { obj.Dispose(); }
}

For more on this topic, start by reading the following articles:

Bruce Eckel: http://www.mindview.net/WebLog/log-0050


Ian Griffiths: http://www.interact-sw.co.uk/iangblog/2004/03/14/generics
Charles Cook: http://www.cookcomputing.com/blog/archives/000425.html
14.4 What's new in the .NET 2.0 class library?

Here is a selection of new features in the .NET 2.0 class library:


Generic collections in the System.Collections.Generic namespace.
The System.Nullable type. (Note that C# has special syntax for this type, e.g. int? is equivalent to Nullable)
The GZipStream and DeflateStream classes in the System.IO.Compression namespace.
The Semaphore class in the System.Threading namespace.
Wrappers for DPAPI in the form of the ProtectedData and ProtectedMemory classes in the System.Security.Cryptography namespace.
The IPC remoting channel in the System.Runtime.Remoting.Channels.Ipc namespace, for optimised intra-machine communication.

and many, many more. See http://msdn2.microsoft.com/en-us/library/t357fb32(en-US,VS.80).aspx for a comprehensive list of changes.

Software Interview question Bank

.NET Interview question Covers LINQ and Silver light book http://www.questpond.com/SampleDotNetInterviewQuestionBook.zip

C# projects Ebook http://www.questpondcom/CSharpProjects.zip

SQL Server Interview questions Ebook http://www.questpond.com/SampleSQlServer.zip

Software testing Ebook http://www.questpond.com/SampleSoftwaretestinginterview.zip

Interview Technical based ASP DOT NET Questions


1.How many languages .NET is supporting now?

Ans :When .NET was introduced it came with several languages. VB.NET, C#, COBOL and Perl, etc. The site DotNet Languages. Net says 44
languages are supported..

2.How is .NET able to support multiple languages?

Ans :A language should comply with the Common Language Runtime standard to become a .NET language. In .NET, code is compiled to
Microsoft Intermediate Language (MSIL for short). This is called as Managed Code. This Managed code is run in .NET environment. So after
compilation to this IL the language is not a barrier. A code can call or use a function written in another language..

3.How ASP .NET different from ASP?

Ans :Scripting is separated from the HTML, Code is compiled as a DLL, and these DLLs can be executed on the server.

4.What is smart navigation?

Ans :The cursor position is maintained when the page gets refreshed due to the server side validation and the page gets refreshed.

5.What is view state?

Ans :The web is stateless. But in ASP.NET, the state of a page is maintained in the in the page itself automatically. How? The values are
encrypted and saved in hidden controls. this is done automatically by the ASP.NET. This can be switched off / on for a single control.

6.How do you validate the controls in an ASP .NET page?

Ans :Using special validation controls that are meant for this. We have Range Validator, Email Validator.

7.Can the validation be done in the server side? Or this can be done only in the Client side?

Ans :Client side is done by default. Server side validation is also possible. We can switch off the client side and server side can be done..

8.How to manage pagination in a page?

Ans :Using pagination option in DataGrid control. We have to set the number of records for a page, then it takes care of pagination by itself..

9.What is ADO .NET and what is difference between ADO and ADO.NET?

Ans :ADO.NET is stateless mechanism. I can treat the ADO.Net as a separate in-memory database where in I can use relationships between the
tables and select insert and updates to the database. I can update the actual database as a batch..

10.Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe


in the page loading process.

Ans :inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received
(usually a file with .aspx extension),the ISAPI filter aspnet_isapi.dll takes care of it by passing the request tothe actual worker process
aspnet_wp.exe..

11.What?s the difference between Response.Write() and Response.Output.Write()?

Ans :The latter one allows you to write formatted output..

12.What methods are fired during the page load?

Ans :Init() - when the pageis instantiated, Load() - when the page is loaded into server memory,PreRender() - the brief moment before the page is
displayed to the user asHTML, Unload() - when page finishes loading..

13.Where does the Web page belong in the .NET Framework class hierarchy?
Ans :System.Web.UI.Page .

14.Where do you store the information about the user?s locale?

Ans :System.Web.UI.Page.Culture .

15.What?s the difference between Codebehind="MyCode.aspx.cs" andSrc="MyCode.aspx.cs"?

Ans :CodeBehind is relevant to Visual Studio.NET only.

16.What?s a bubbled event?

Ans :When you have a complex control, like DataGrid, writing an event processing routine for each object (cell, button,row, etc.) is quite tedious.
The controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents..

17.Suppose you want a certain ASP.NET function executed on MouseOver over a


certain button. Where do you add an event handler?

Ans :It?s the Attributesproperty, the Add function inside that property. So
btnSubmit.Attributes.Add("onMouseOver","someClientCode();") A simple?Javascript:ClientCode();? in the button control of the .aspx page will
attach the handler (javascript function)to the onmouseover event..

18.What data type does the RangeValidator control support?

Ans :Integer,String and Date..

19.Where would you use an iHTTPModule, and what are the limitations of any
approach you might take in implementing one?

Ans :One of ASP.NET?s most useful features is the extensibility of the HTTP pipeline, the path that data takes between client and server. You
can use them to extend your ASP.NET applications by adding pre- and post-processing to each HTTP request coming into your application. For
example, if you wanted custom authentication facilities for your application, the best technique would be to intercept the request when it comes
in and process the request in a custom HTTP module..

20.Explain what a diffgram is and a good use for one?

Ans :A DiffGram is an XML format that is used to identify current and original versions of data elements. The DataSet uses the DiffGram format
to load and persist its contents, and to serialize its contents for transport across a network connection. When a DataSet is written as a DiffGram, it
populates the DiffGram with all the necessary information to accurately recreate the contents, though not the schema, of the DataSet, including
column values from both the Original and Current row versions, row error information, and row order..

Interview questions on Design patterns

Q1. What are design patterns?


Q2. Can we always apply the same solution to different problems at hand?.
Q3.What should be the level of detail/abstraction which should be provided by a design pattern?

Q4. What are the most common problems which one faces during the application design phase that are solved by design patterns?
Q5. How does one decide which Design pattern to use in our application?
Q6. What is Refactoring?
Q7. What are Antipatterns?
SPECIFIC PATTERNS
Q8. As we do development in tiers, how do we divide patterns in tiers?

Q9. What is Intercepting Filter pattern?


Q10. What is Front Controller pattern?
Q11. What is View Helper pattern?
Q12. What is Composite View pattern?
Q13. What is Service to Worker pattern?
Q14. What is Dispatcher View pattern?
Q15. What is Business Delegate pattern? .
Q16. What is Value Object (VO) pattern?

Q17. What is Session Façade pattern?


Q18. What is Value Object Assembler pattern?
Q19. What is Value List Handler pattern?
Q20. What is Service Locator pattern?
Q21. What is Data Access Object pattern?
Q22. What is EJB Command pattern?
Q23. What is Version Number pattern?
Q24. What all patterns are used to improve performance and scalability of the application?
Q25. What design patterns could be used to manage security?

Gnanz.../
http://gnanz-flexworld.blogspot.com
MCTS Dumps www.dumpsquestions.com
http://www.free-ebooks-download.org/free-ebook/dotnet/MCTS
%20Dumps/Actual_Tests_070_528_447_536_431_441_447_444_443_526_529_528_536_549_340.php

http://www.free-ebooks-download.org/free-ebook/dotnet/MCTS%20Dumps/Pass4Sure_070_630_431_547_528_536.php

http://www.free-ebooks-download.org/free-ebook/dotnet/MCTS%20Dumps/mcpd-70-547.php

http://www.free-ebooks-download.org/free-ebook/dotnet/MCTS%20Dumps/mcpd-70-548.php

http://www.free-ebooks-download.org/free-ebook/dotnet/MCTS%20Dumps/mcpd-70-528.php

http://www.free-ebooks-download.org/free-ebook/dotnet/MCTS%20Dumps/mcpd-70-536.php

41 - 50 Common Interview Questions and Answers


41. If you were hiring a person for this job, what would you look for?
Be careful to mention traits that are needed and that you have.

42. Do you think you are overqualified for this position?


Regardless of your qualifications, state that you are very well
qualified for the position.

43. How do you propose to compensate for your lack of experience?


First, if you have experience that the interviewer does not know about,
bring that up: Then, point out (if true) that you are a hard working
quick learner.

44. What qualities do you look for in a boss?


Be generic and positive. Safe qualities are knowledgeable, a sense of
humor, fair, loyal to subordinates and holder of high standards. All
bosses think they have these traits.

45. Tell me about a time when you helped resolve a dispute betweenothers.
Pick a specific incident. Concentrate on your problem solving technique
and not the dispute you settled.

46. What position do you prefer on a team working on a project?


Be honest. If you are comfortable in different roles, point that out.

47. Describe your work ethic.


Emphasize benefits to the organization. Things like, determination to
get the job done and work hard but enjoy your work are good.

48. What has been your biggest professional disappointment?


Be sure that you refer to something that was beyond your control. Show
acceptance and no negative feelings.

49. Tell me about the most fun you have had on the job.
Talk about having fun by accomplishing something for the organization.

50. Do you have any questions for me?


Always have some questions prepared. Questions prepared where you will be an asset to the organization are good. How soon will I be able to be
productive? and What type of projects will I be able to assist on? are
examples.

.Net Interview Questions


1.What is .NET?

2.How many languages .NET is supporting now?


3.How is .NET able to support multiple languages?

4.How ASP .NET different from ASP?

5.What is smart navigation?

6.What is view state?

7.How do you validate the controls in an ASP .NET page?

8.Can the validation be done in the server side? Or this can be done only in the Client side?

9.How to manage pagination in a page?

10.What is ADO .NET and what is difference between ADO and ADO.NET?

11.Observations between VB.NET and VC#.NET?

12.Advantages of migrating to VB.NET ?

13.Using ActiveX Control in .Net

14.What is Machine.config?

15.What is Web.config?

16.What is the difference between ADO and ADO.NET?

17.What is the difference between VB and VB.NET?

18.What is a Strong Name?

19.What is a Manifest?

20.Creating a Key Pair?

21.What is the difference between "using System.Data;" and directly adding the reference from "Add References Dialog Box"?

22.What is GAC?

23.What is a Metadata?

24.What is managed code and managed data?

25.What is .NET / .NET Framework?

26.What is Reflection?

27.What is "Common Type System" (CTS)?

28.What is "Common Language Specification" (CLS)?

29.What is "Common Language Runtime" (CLR)?

30.What are Attributes?

31.What are the Types of Assemblies?

32.What is an Intermediate language?

33.What is the difference between ASP and ASP.NET?

34.Using COM Component in .Net ?

35.What is an assembly?

36.What is a Web Service?


37.webFarm Vs webGardens

38.What is the difference between a namespace and assembly name?

39.What’s a Windows process?

40.What’s typical about a Windows process in regards to memory allocation?

41.Explain what relationship is between a Process, Application Domain, and Application?

42.What are possible implementations of distributed applications in .NET?

43.What are the consideration in deciding to use .NET Remoting or ASP.NET Web Services?

44.What’s a proxy of the server object in .NET Remoting?

45.What are remotable objects in .NET Remoting?

46.What are channels in .NET Remoting?

47.What security measures exist for .NET Remoting in System.Runtime.Remoting?

48.What is a formatter?

49.Choosing between HTTP and TCP for protocols and Binary and SOAP for formatters, what are the trade-offs?

50.What’s SingleCall activation mode used for?

.NET interview question- Part 1

1) Explain .NET architecture?


It is a foundation class from which it is essential to build robust application. It consist of windows form, web form and
console application. It is basically a collection of classes and service.

2) What language does the .NET framework support?


Some of the languages supported by .NET are C#, VB.NET, C++.NET. Any language that has a compiler that is
capable of compiling the code to MSIL .NET framework support that language.

3) How is ASP.NET differ from ASP?


The HTML code separated from the scripting language, the compiler compiles as dll and the DLL executed on the
server.

4) How to manage pagination in a page?


Pagination can be managed using datagrid were we have option to select the number of pages, thus it take care of
pagination.

5) Can the validation be done in the server side or client side?


By default the validation is done in the client side. Even server side validation is possible, for this it require to switch
from client side to server side.

6) Which control do not have events?


These are the fallowing controls do not have any events
1. DirectorySearcher
2. Directory Entry
3. FolderBrowserDialog
4. ImageList
5. HelpProvider

7) What is CLR?
CLR stands for Common Language Runtime. CLR is equal to JVM. Under runtime it converts MSIL into machine
language code, which is then executed.
8) What are the responsibilities of CLR?
Some of the responsibilities of CLR are:-
* Code verification
* Garbage collection
* Code access Security
* Intermediate Language.

9) What is CTS?
CTS stands common type system which defines the basic type which can be used in the .NET environment and the
operation on these type are performed.

10) What is web.config?


Web.config is a collection of setting such as session date, database, security and error handling.

11)What is the advantage of VB.NET?


* It manages execution of the code.
* It is object oriented language.
* Security
* It uses XML to transfer data between various layer.

12) Which controls cannot be placed in MDI?


It is not possible to place all the controls in MDI. Only certain controls can be placed, such as status bar,
progressive bar, picture box and timer.

13) What is the root class in .NET?


The root class in .NET is System.object.

14) What is serialization? How it works in .NET?


Serialization is a process that convert objects into bytes. IT is a process that save the session state.

15) What is a web service?


It is a software component which exposes itself through open communication. It is a group of function that are
packaged together to form a common network.

16) What is an interface?


An interface is an entity, which just have the definition of methods and not the implementation. Since c# doesn’t
support multiple inheritance it make use of the interface.

17) What is a strong name?


It includes the vdersion number, identity, public token and the name of assembly.

18) What do you know about .NET assemblies?


Assemblies are the building block of the program, it is also referred as smallest unit of deployment and version.

19) What is the difference between private and shared assembly?


Shared assembly is used by multiple application and should have a strong name. Private assembly is used inside
an application and they don’t require strong name.

20) What does WSDL stand for?


Web service description language also known as WSDL is an XML representation of the web service interface.
It consist of two types of operation:-
* Result oriented operations
* Document oriented operations

21) What is reflection in Microsoft.NET context?


Reflection in Microsoft.NET is used to read about metadata details like method, reference and type that are derived
from system.assembly.reflection class object.

22)What does managed mean in the .NET context?


Managed code is the code that run in the CLR environment. The manage code doesn’t make any harm to the
programmer knowingly or unknowingly. IT is a secured code.

23)What is an application Domain?


Runtime environments and OS provides isolation between application . It essential to ensure that the isolated code
don’t affect the other application.

24)What is isapi?
ISAPI stands for Internet server Application Programming interface, it allows the developer to extend IIS by writing
components that can process the request raw.

25)What is CAS?
CAS stands for code access security it is a part of .NET security model to check whether it is safe to run piece of
code and to find the necessary resources required for the code.

You might also like