40
Interview Questions in ASP.NET,C#.NET,SQL Server,.NET Framework By: Suresh Dasari Nov 13, 2013 Categories: Interview Questions Here I am posting the interview questions whatever i have faced in my interviews I have searched for so many websites and gathered information from my friends to answer the questions perfectly. i think these questions are very helpful for the people who are trying to get the job on .NET The most common question for experience persons is Why would you like to change the company? 1) I am looking for a more challenging career in a firm with a larger employee base such as yours. 2) Keeping in mind my career goals, the time has come for me to move onto the next rung of the ladder and make a mark for myself. This can be achieved in a company like this. 3) It is just a career move to enhance my knowledge in my own area of interest. After completion of this question only interview will go for further questions Difference between stored procedure and function 1) Procedure can return zero or n values whereas function can return one value which is mandatory. 2) Procedures can have input, output parameters for it whereas functions can have only input parameters. 3) Procedure allows select as well as DML statement in it whereas function allows only select statement in it. 4) Functions can be called from procedure whereas procedures cannot be called from function. 5) Exception can be handled by try-catch block in a procedure whereas try- catch block cannot be used in a function. 6) We can go for transaction management in procedure whereas we can't go in function. 7) Procedures cannot be utilized in a select statement whereas function can be embedded in a select statement.

Interview Questions in ASP

Embed Size (px)

DESCRIPTION

Interview Questions in ASP

Citation preview

Page 1: Interview Questions in ASP

Interview Questions in ASP.NET,C#.NET,SQL Server,.NET FrameworkBy: Suresh Dasari Nov 13, 2013

Categories: Interview QuestionsHere I am posting the interview questions whatever i have faced in my interviewsI have searched for so many websites and gathered information from my friends to answer the questions perfectly.

i think these questions are very helpful for the people who are trying to get the job on .NETThe most common question for experience persons is

Why would you like to change the company?

1) I am looking for a more challenging career in a firm with a larger employee base such as yours.2) Keeping in mind my career goals, the time has come for me to move onto the next rung of the ladder and make a mark for myself. This can be achieved in a company like this.3) It is just a career move to enhance my knowledge in my own area of interest.After completion of this question only interview will go for further questions

Difference between stored procedure and function

1) Procedure can return zero or n values whereas function can return one value which is mandatory.2) Procedures can have input, output parameters for it whereas functions can have only input parameters.3) Procedure allows select as well as DML statement in it whereas function allows only select statement in it.4) Functions can be called from procedure whereas procedures cannot be called from function.5) Exception can be handled by try-catch block in a procedure whereas try-catch block cannot be used in a function.6) We can go for transaction management in procedure whereas we can't go in function.7) Procedures cannot be utilized in a select statement whereas function can be embedded in a select statement.

Difference between Abstract and Interface

Abstract Class:

-Abstract class provides a set of rules to implement next class-Rules will be provided through abstract methods-Abstract method does not contain any definition-While inheriting abstract class all abstract methods must be override-If a class contains at least one abstract method then it must be declared as an “Abstract Class”-Abstract classes cannot be instantiated (i.e. we cannot create objects), but a reference can be created-Reference depends on child class object’s memory

Page 2: Interview Questions in ASP

-Abstract classes are also called as “Partial abstract classes”-Partial abstract class may contain functions with body and functions without body-If a class contains all functions without body then it is called as “Fully Abstract Class” (Interface)

Interface:

-If a class contains all abstract methods then that class is known as “Interface”-Interfaces support like multiple inheritance-In interface all methods r public abstract by default-Interfaces r implementable-Interfaces can be instantiated, but a reference cannot be created

Index types in SQL Server

Clustered Index

Only 1 allowed per table physically rearranges the data in the table to confirm to the index constraints for use on columns that are frequently searched for ranges of data for use on columns with low selectivity.

Non-Clustered Index

Up to 249 allowed per table creates a separate list of key values with pointers to the location of the data in the data pages For use on columns that are searched for single values 

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

Included Column Index (New in SQL Server 2005) 

In SQL Server 2005, the functionality of non-clustered indexes is extended by adding non-key columns to the leaf level of the non-clustered index. Non-key columns can help to create cover indexes. By including non-key columns, you can create non-clustered indexes that cover more queries. The Database Engine does not consider non-key columns when calculating the number of index key columns or index key size. Non-key columns can be included in non-clustered index to avoid exceeding the current index size limitations of a maximum of 16 key columns and a maximum index key size of 900 bytes. Another advantage is that using non-key column in index we can have index data types not allowed as index key columns generally.

In following example column Filename is varchar(400), which will increase the size of the index key bigger than it is allowed. If we still want to include in our cover index to gain performance we can do it by using the Keyword INCLUDE.

Page 3: Interview Questions in ASP

USE AdventureWorksGOCREATE INDEX IX_Document_TitleON Production.Document (Title, Revision)INCLUDE (FileName)

Non-key columns can be included only in non-clustered indexes. Columns can’t be defined in both the key column and they INCLUDE list. Column names can’t be repeated in the INCLUDE list. Non-key columns can be dropped from a table only after the non-key index is dropped first. For Included Column Index to exist there must be at least one key column defined with a maximum of 16 key columns and 1023 included columns. 

Avoid adding unnecessary columns. Adding too many index columns, key or non-key as they will affect negatively on performance. Fewer index rows will fit on a page. This could create I/O increases and reduced cache efficiency. More disk space will be required to store the index. Index maintenance may increase the time that it takes to perform modifications, inserts, updates, or deletes, to the underlying table or indexed view.

Another example to test:

Create following Index on Database AdventureWorks in SQL SERVER 2005

USE AdventureWorksGOCREATE NONCLUSTERED INDEX IX_Address_PostalCodeON Person.Address (PostalCode)INCLUDE (AddressLine1, AddressLine2, City, StateProvinceID)GO 

Test the performance of following query before and after creating Index. The performance improvement is significant.SELECT AddressLine1, AddressLine2, City, StateProvinceID, PostalCodeFROM Person.AddressWHERE PostalCode BETWEEN '98000'AND '99999';GO

Interview questions 

What are differences between Array list and Hash table?

Ans: 1) Hash table store data as name, value pair. While in array only value is store.2) To access value from hash table, you need to pass name. While in array, to access value, you need to pass index number.3) you can store different type of data in hash table, say int, string etc. while in array you can store only similar type of data.

Page 4: Interview Questions in ASP

What are differences between system.stringbuilder and system.string?

The main difference is system.string is immutable and system.stringbuilder is a mutable. Append keyword is used in string builder but not in system.string.Immutable means once we created we cannot modified. Suppose if we want give new value to old value simply it will discarded the old value and it will create new instance in memory to hold the new value.

What are the differences between Application object and session object?

Ans: The session object is used to maintain the session of each user. If one user enter in to the application then they get session id if he leaves from the application then the session id is deleted. If they again enter in to the application they get different session id.But for application object the id is maintained for whole application. 

What are the different types of indexes?

Ans: Two types of indexes are there one is clustered index and non-clustered index

How many types of memories are there in .net? 

Ans: Two types of memories are there in .net stack memory and heap memory

Is it possible to set the session out time manually? 

Ans: Yes we can set the session out time manually in web.config.

What are differences between function and stored procedure?

Ans:1) Function returns only one value but procedure returns one or more than one value.2) Function can be utilized in select statements but that is not possible in procedure.3) Procedure can have an input and output parameters but function has only input parameters only.4) Exceptions can be handled by try catch block in procedures but that is not possible in function.

What are the differences between Abstract and interface?

Ans:  1) Abstract cannot be instantiated but we can inherit. Interface it cannot be inherit it can be instantiate2) Interface contain only declarations no definitions. Abstract contain declarations and definitions.3) The class which contains only abstract methods is interface class. A class which contains abstract method is called abstract class4) Public is default access specifier for interface we don’t have a chance to declare other specifiers. In abstract we have chance to declare with any access specifier

Page 5: Interview Questions in ASP

Can you Explain Page lifecycle in .net?Can you Explain .NET architecture in .net?

What is the difference between primary key and unique key with not null?

Ans: There is no difference between primary key and unique key with not null.

What is boxing and unboxing concepts in .net? 

Ans: Boxing is a process of converting value type into reference typeUnboxing is a process of converting reference type to value type.

What are the differences between value type and reference type?

Ans: Value type contain variable and reference type are not containing value directly in its memory.Memory is allocated in managed heap in reference type and in value type memory allocated in stack. Reference type ex-class value type-struct, enumeration

Is it possible to host the website from desktop?

Ans: Yes 

Why we go for page rendering in Asp.Net Page life cycle?

Ans: Browser understands an only html control that’s why in page rendering we will convert the aspx controls into html controls.

Write a sample query for self join?

Ans: Select e1.ename, e2.empid from emp e1, emp e2 where e1.empid=e2.mgrid;

Can we change the index of primary key on table?

Ans: No

How to change the name of the table or stored procedure in sql?

Ans: sp_rename oldtablename newtablenameFor changing the column nameSp_rename  ‘tablename.[Oldcolumnname]’,’newcolumnname’,’Column’Ex:sp_rename ‘tblemp.first’,’namechange’,’Column’

Page 6: Interview Questions in ASP

How to find out which index is defined on table?

Ans: sp_helpindex tablename

Can you write the program to find the length of string without using library function?

Ans: for (int i=0; str[i]!=”\n”; i++){Count++;}

What is the difference between scope_identity() and current_identity()?

Ans: Scope_identity and current _identity both are similar and it will return the last identity value generated in the table.Scope_Identity will return the identity value in table that is currently in scope

What are difference between GET and POST Methods?

Ans:GET Method (): 

1) Data is appended to the URL. 2) Data is not secret. 3) It is a single call system 4) Maximum data that can be sent is 256. 5) Data transmission is faster 6) this is the default method for many browsers 

POST Method (): 

1) Data is not appended to the URL. 2) Data is Secret 3) it is a two call system. 4) There is no Limit on the amount of data. That is characters any amount of data can be sent. 5) Data transmission is comparatively slow. 6) No default and should be explicitly specified.

What are difference between truncate and delete?

Ans: 1) Delete keep the lock over each row where Truncate keeps the lock on table not on all the row.2) Counter of the Identity column is reset in Truncate where it is not reset in Delete. 3) Trigger is not fired in Truncate where as trigger is fired in Delete.4) In TRUNCATE we cannot rollback.5) In DELETE we can rollback

Page 7: Interview Questions in ASP

What is the difference Grid View and between Data Grid (Windows)?

Ans:1) GridView Control Enables you to add sorting, paging and editing capabilities without writing any code. 2)GridView Control Automatically Supports paging by setting the ‘PagerSetting’ Property.The Page Setting Property supports four Modles 

a. Numeric(by default) b. Next Previous c. NumericFirstLast d. Next PreviousLast 

3)It is Used in asp.net 4)GridView Supports RowUpdating and RowUpdated Events. 5)GidView is Capable of Pre-Operations and Post-Operations. 6)GridView Has EditTemplates for this control 7)It has AutoFormat 

DataGrid(Windows) 

1)DataGid Control raises single Event for operations 2)DataGird Supports the SortCommand Events that occur when a column is Soted. 3)DataGrid Supports UpdataCommand Event that occurs when the UpdateButton is clicked for an item in the grid. 4)DataGrid is used in Windows GUI Application. 5)It doesnot have EditTemplates for this control 6)It doesnot have AutoFormat

If I write System.exit (0); at the end of the try block, will the finally block still execute?

Ans: No in this case the finally block will not execute because when you say system.exit(0),the control immediately goes out of the program, and thus finally never executes.

What are the different levels of State management in ASP.NET?

Ans:State management is the process by which you maintain state and page information over multiple requests for the same or different pages.

There are 2 types State Management: 

1. Client – Side State Management This stores information on the client's computer by embedding the information into a Web page, a uniform resource locator (url), or a cookie. The techniques available to store the state information at the client end are listed down below: 

a. View State – Asp.Net uses View State to track the values in the Controls. You can add custom values to the view state. It 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

Page 8: Interview Questions in ASP

the page is posted, one of the first tasks performed by page processing is to restore view state. 

b. Control State – If you create a custom control that requires view state to work properly, you should use control state to ensure other developers don’t break your control by disabling view state. 

c. Hidden fields – Like view state, hidden fields store data in an HTML form without displaying it in the user's browser. The data is available only when the form is processed. 

d. Cookies – Cookies store a value in the user's browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be available for multiple Web pages on a web site. 

e. Query Strings - Query strings store values in the URL that are visible to the user. Use query strings when you want a user to be able to e-mail or instant message state data with a URL. 

2. Server – Side State Management a. Application State - Application State information is available to all pages, regardless of which user requests a page. 

b. Session State – Session State information is available to all pages opened by a user during a single visit. 

Both application state and session state information is lost when the application restarts. To persist user data between application restarts, you can store it using profile properties.

Abstract Class:

Abstract class is a class which can’t be instantiate. Class should have “Abstract” key word with the name.  In any one of the method of class having abstract method with in it, then it should be define as abstract class. The class which derived the abstract class should have definition of the abstract method. These classes which derived the abstract class and implement the abstract methods call concrete class.Abstract class may have the definition of function or may not.  Below is the simple example of an abstract classpublic abstract alass AbstractStudent    {        String Roll        {            get;            set;        }

        String FirstName        {            get;            set;        }                String LastName        {            get;            set;

Page 9: Interview Questions in ASP

        }        

        Public String GetStudentDetails()             {

                  // Implementation of Method                 }

        public String SaveStudentDetails ()            {                  // Implementation of Method                 }

        public abstract String CalculateWage();

    }So, the class having one abstract method so we need to mention the class as "abstract" .

Difference between Abstract Class and Interface?

Abstract class is a class which can’t be instantiated and which can have methods with definition as well as declaration also. This can be inherited.  

As for Example:

public abstract class AbstractStudent    {        String Roll        {            get;            set;        }

        String FirstName        {           get;           set;        }           String LastName        {           get;            set;        }

        Public String GetStudentDetails()            {                 // Implementation of Method                }

        public String SaveStudentDetails ()            {                  // Implementation of Method               }

Page 10: Interview Questions in ASP

        public abstract String CalculateWage();

    }

Interface can only contain the methods declaration and can be implemented in the class.

As for Example:Public interface IStudnet    {        String Roll        {           get;            set;        }

        String FirstName        {            get;            set;        }            String LastName        {            get;            set;        }           String GetStudentDetails();        String SaveStudentDetails ();    }

Below are the few main difference between Abstract Class and Interface

a.    In abstract class method can have definition as well as declaration also. But Interface should have only definition.b.    All the Methods are Public as default and don’t have any access Modifier Controls in interface, whereas for abstract class we can have access modifier for methods.c.    Abstract class can have constructor or destructor, whereas interface not.d.    Abstract class can’t be part of multiple inheritance and we can implement multiple interface.

What do you mean by String objects are immutable?

String objects are immutable as its state cannot be modified once created. Every time when we perform any operation like add, copy, replace, and case conversion or when we pass a string object as a parameter to a method a new object will be created.

Example:String str = "ABC";

str.Replace("A","X");

Page 11: Interview Questions in ASP

Here Replace() method will not change data that "str" contains, instead a new string object is created to hold data "XBC" and the reference to this object is returned by Replace() method.

So in order to point str to this object we need to write below line.str = str.Replace("A","X");Now the new object is assigned to the variable str. earlier object that was assigned to str will take care by garbage collector as this one is no longer in used.

What is dll hell problem in .NET and how it will solve?

Ans: Dll hell, is kind of conflict that occurred previously, due to the lack of version supportability of dll for (within) an application.NET Framework provides operating system with a global assembly cache. This cache is a repository for all the .net components that are shared globally on a particular machine. When a .net component installed onto the machine, the global assembly cache looks at its version, its public key and its language information and creates a strong name for the component. The component is then registered in the repository and indexed by its strong name, so there is no confusion between the different versions of same component, or DLL

What is a Partial class?

Ans: Instead of defining an entire class, you can split the definition into multiple classes by using partial class keyword. When the application compiled, c# compiler will group all the partial classes together and treat them as a single class. There are a couple of good reasons to use partial classes. Programmers can work on different parts of classes without needing to share same physical fileEx:Public partial class employee{Public void somefunction(){}}Public partial class employee{Public void function (){}}

What is difference between constants, read-only and, static?

Constants: The value can’t be changed

Read-only: The value will be initialized only once from the constructor of the class.

Static: Value can be initialized once.

Page 12: Interview Questions in ASP

What is the cross page post backing?

Asp.Net 2.0 fixed this with built-in features that allowed us to easily send information from one page to another.

Button control has property PostBackUrl that can be set to URL of any page in our ASP.Net WebSite where we want to transfer all form values to.Along with that Asp.Net 2.0 Page class has a property PreviousPage that allows us to get reference to the Page object that initiated the postback (in other words to get the actual reference to the Page object of the aspx page on which user clicked the Submit button on a HTML form).

So for example lets create two sample pages in our Web Application:   SourcePage.aspx DestinationPage.aspx

In SoucePage in Html form we will put two TextBox controls (one for First Name and one for Last Name) and one Button component  and set its PostBackUrl property to "~/DestinationPage.aspx". 

SourcePage.aspx:    <form id="form1" runat="server">        <div>            First Name:&nbsp;<asp:TextBox ID="FirstName" runat="server"></asp:TextBox><br />            Last Name:&nbsp;<asp:TextBox ID="LastName" runat="server"></asp:TextBox><br /><br />            <asp:Button ID="Button1" runat="server" Text="Submit To Destination Page"PostBackUrl="~/CrossPagePostbacks/DestinationPage.aspx" />        </div>    </form>

When our user clicks the Submit button, all the values from the HTML Form on SourcePage.aspx will be transfered to the DestinationPage.aspx and we will also be able to get reference to the SourcePage.aspx in our DestinationPage with the PreviousPage property like this:

So in our DestinationPage.aspx.cs code-behind we can easily access two TextBox controls on SourcePage.aspx and show them in two label controls like this:    protected void Page_Load(object sender, EventArgs e)    {        // first check if we had a cross page postback        if ( (PreviousPage != null) && (PreviousPage.IsCrossPagePostBack) )        {            Page previousPage = PreviousPage;            TextBox firstName = (TextBox)previousPage.FindControl("FirstName");            TextBox lastName = (TextBox)previousPage.FindControl("LastName");            // we can now use the values from TextBoxes and display them in two Label controls..            labelFirstName.Text = firstName.Text;            labelLastName.Text = lastName.Text;         }    }

Page 13: Interview Questions in ASP

You probably noticed that we first checked if PreviousPage property of current page (DestinationPage.aspx) is NOT NULL, this is done to avoid running our code in case that user opens our DestinationPage.aspx directly, without running a cross page postback.

Also here we checked the another PreviousPage property called IsCrossPagePostBack to see if we really had a CrossPagePostback.(If Server.Transfer is used to redirect to this page, IsCrossPagePostBack property will be set to FALSE.

TIP: We can be completely sure that we have a  real CrossPagePostback ONLY IF:1. Page.PreviousPage is NOT NULL,2. PreviousPage.IsCrossPagePostback is true

This important to check to avoid errors in code.

Now this is very useful and i'm sure you are eager to use this in your next project. But wait, we are not over yet!

Finding the controls on PreviousPage with FindControl method and type-casting them from object to their real type is a little messy.It feels like there must be a better solution for this!

And here it is: We can use the <%@ PreviousPageType %> directive in the header of our DestinationPage.aspx like this    <%@ PreviousPageType VirtualPath="~/SourcePage.aspx" %>

to declare our previous page type, and then we can access Public properties of the PreviousPage without typecasting.Now all we need to do is to create some public properties on our SourcePage.aspx.cs to expose data/Controls we want to the destionation page:    public partial class SourcePage : System.Web.UI.Page    {        public string FormFirstName        {            get { return FirstName.Text; }        }

        public string FormLastName        {            get { return LastName.Text; }        }    }

And then we can change the Page_Load code in our DestinationPage.aspx to much cleaner code like this:    protected void Page_Load(object sender, EventArgs e)    {        // first check if we had a cross page postback        if ( (PreviousPage != null) && (PreviousPage.IsCrossPagePostBack) )        {            SourcePage prevPage = PreviousPage;

            // we can now use the values from textboxes and display them in two Label controls..            labelFirstName.Text = prevPage.FormFirstName;            labelLastName.Text = prevPage.FormLastName;     

Page 14: Interview Questions in ASP

        }    }

SourcePage type used in the code is offcourse name of the partial class defined is

SourcePage.aspx.cs that inherits System.Web.UI.Page that is automatically created for us

when we created new WebForm in VisualStudio.

This code is much cleaner and easier to follow, there is no ugly typecasting, just simple

property values to use to retrieve the data from previous page.

When should you use Abstract Class vs Interface while programming?

 Ans: When we want that sub class must implement all the methods of base class. In such a

situation we will implement the interface. In the other hand when we want only some

method of base class in our sub class then use base class as abstract class.

What is the difference between application exception and system exception?

Ans: The difference between application exception and system exception is that system

exceptions are thrown by CLR and application exceptions are thrown by applications.

What is the difference between authorization and authentication?

Ans: Authorization is a process of allowing or denying resources to particular user or record 

Declaration of authorization is

<authorization><allow users=”Suresh, Sanjay”/><deny users=”Ramana, Rakesh”></authorization>Sometimes authorization allows the unauthorized persons at that time we will use<deny users=”?”/>

Authentication means 

Authentication is a process where we identify the credentials of user i.e. username, password and create an identity to mention user as an authenticated.  

What is the use of n-tier architecture and 3-tier architecture?

Page 15: Interview Questions in ASP

Check this article for 3-tier architecture 3 tier architecture example in asp.net

How to get the version of the assembly?

Ans: lbltxt.text=Assembly. GetExecutingAssembly().GetName().Version.ToString();

What is the location of Global Assembly Cache on the system?

Ans: c:\Windows\assembly

 What is the serialization?

Ans: Serialization is a process of converting object into a stream of bites.

What is synchronization?

Ans: The mechanism needed to block one thread access to the data. If the data is being accessed by another thread.Synchronization can be accessed by using system.monitor classA monitor class methods are enter, exit, pulse for this lock statement is also usedSuppose if we need to synchronize some data at that time we need to place that data in this blockLock{}Whatever the data has been placed into the lock block that data has been blocked

What are the thread priority levels?

Ans: Thread priority levels are five types         0 - Zero level         1 - Below Normal         2 - Normal         3 - Above Normal         4 - HighestBy Default priority level is 2

What is the difference between .tostring(), Convert.tostring()?

Ans: The basic difference between them is “Convert” function handles NULLS while“.ToString()” does not it will throw a NULL reference exception error. So as a good codingpractice using “convert” is always safe.

What is Collation?

Ans: Collation refers to a set of rules that determine how the data is sorted and compared.

Page 16: Interview Questions in ASP

What is the difference between Primary key and unique key?

Ans: Primary key does not allow the null values but unique key allows one null value.Primary key will create clustered index on column but unique key will create non-clustered index by default.

How many web.config files are there in 1 project?

Ans: There might be multiple web.config files for a single project depending on the hierarchy of folders inside the root folder of the project, so for each folder we can use one web.config file

What is the difference between throw and throw ex?What is the difference between view state and hidden field?

Ans: viewstate is secured hidden field is insecureViewstate will store large amount of data but hidden filed will store small amount of data. 

What is the difference between binary serialization and xml serialization?What is the Difference between read only and constant variables?

Ans: Read only can assign the values at runtime only.Constant will assign the values at compile time only.We cannot modify the both variable values.

What is static keyword in .Net?

Ans: Static is same as constant variable but we can change the value of static variable and we can access the variables without creating any instances

What is the use of business logic layer in 3-tier architecture in .net?

Ans: Though a web site could talk to the data access layer directly, it usually goes through another layer called the business layer. The business layer is vital in that it validates the input conditions before calling a method from the data layer. This ensures the data input is correct before proceeding, and can often ensure that the outputs are correct as well. This validation of input is called business rules, meaning the rules that the business layer uses to make “judgments” about the data.

However, business rules don’t only apply to data validation; these rules apply to any calculations or any other action that takes place in the business layer. Normally, it’s best to put as much logic as possible in the business layer, which makes this logic reusable across applications.

One of the best reasons for reusing logic is that applications that start off small usually grow in functionality. For instance, a company begins to develop a web site, and as they realize

Page 17: Interview Questions in ASP

their business needs, they later decide to add a smart client application and windows service to supplement the web site. The business layer helps move logic to a central layer for “maximum reusability.”

Check this post introduction to 3-tier Architecture

What happens when I enter a URL in my browser and click enter?

You type in the URL and hit go. The browser needs to translate that URL www.somesite.com into an IP address so it knows what computer on the internet to connect to (That URL is just there to make it easier for us humans - kinda like speed-dial for phone numbers I guess). So your browser will see if it already has the appropriate IP address cached away from previous visits to the site. If not, it will make a DNS query to your DNS server (might be your router or your ISP's DNS server) - seehttp://en.wikipedia.org/wiki/Domain_name… for more on DNS. Once your browser knows what IP to use, it will connect to the appropriate webserver and ask for the page. The webserver then returns the requested page and your browser renders it to the screen.

The firewall will control connections to & from your computer. For the most part it will just be controlling who can connect to your computer and on what ports. For web browsing your firewall generally won't be doing a whole lot.

Your router (see http://en.wikipedia.org/wiki/Router ) essentially guides your request through the network, helping the packets get from computer to computer and potentially doing some NAT (seehttp://en.wikipedia.org/wiki/Network_add… ) to translate IP addresses along the way (so your internat LAN request can be transitioned onto the wider internet and back).

IP Addresses (see http://en.wikipedia.org/wiki/IP_address ) are unique addresses for computers that basically allow computers to find each other. Think of the IP address as a computer's well address or phone number, you've got to know someone's phone number before you can call them and you've got to know a computer's IP address before you can connect to it. Going back to the start - that's what those URLS and DNS make possible, you don't know John Doe's phone number so you look in the phone book; likewise your computer doesn't know yahoo.com's IP address so it looks in DNS.

 Define variable and constant.

A variable can be defined as a meaningful name that is given to a data storage location in the computer memory that contains a value. Every variable associated with a data type determines what type of value can be stored in the variable, for example an integer, such as 100, a decimal, such as 30.05, or a character, such as 'A'.

You can declare variables by using the following syntax:

<Data_type> <variable_name> ;

A constant is similar to a variable except that the value, which you assign to a constant, cannot be changed, as in case of a variable. Constants must be initialized at the same time they are declared. You can declare constants by using the following syntax:

const int interestRate = 10;

Page 18: Interview Questions in ASP

2. What is a data type? How many types of data types are there in .NET ?

A data type is a data storage format that can contain a specific type or range of values. Whenever you declare variables, each variable must be assigned a specific data type. Some common data types include integers, floating point, characters, and strings. The following are the two types of data types available in .NET:

Value type - Refers to the data type that contains the data. In other words, the exact value or the data is directly stored in this data type. It means that when you assign a value type variable to another variable, then it copies the value rather than copying the reference of that variable. When you create a value type variable, a single space in memory is allocated to store the value (stack memory). Primitive data types, such as int, float, and char are examples of value type variables.

Reference type - Refers to a data type that can access data by reference. Reference is a value or an address that accesses a particular data by address, which is stored elsewhere in memory (heap memory). You can say that reference is the physical address of data, where the data is stored in memory or in the storage device. Some built-in reference types variables in .Net are string, array, and object.

3. Mention the two major categories that distinctly classify the variables of C# programs.

Variables that are defined in a C# program belong to two major categories: value type and reference type. The variables that are based on value type contain a value that is either allocated on a stack or allocated in-line in a structure. The variables that are based on reference types store the memory address of a variable, which in turn stores the value and are allocated on the heap. The variables that are based on value types have their own copy of data and therefore operations done on one variable do not affect other variables. The reference-type variables reflect the changes made in the referring variables.

Predict the output of the following code segment: 

int x = 42; int y = 12;int w;object o;o = x;w = y * (int)o; Console.WriteLine(w);

/* The output of the code is 504. */

4. Which statement is used to replace multiple if-else statements in code.

In Visual Basic, the Select-Case statement is used to replace multiple If - Else statements and in C#, theswitch-case statement is used to replace multiple if-else statements.

5. What is the syntax to declare a namespace in .NET?

Page 19: Interview Questions in ASP

In .NET, the namespace keyword is used to declare a namespace in the code.

The syntax for declaring a namespace in C# is:namespace UserNameSpace;

The syntax for declaring a namespace in VB is:Namespace UserNameSpace

6. What is the difference between constants and read-only variables that are used in programs?

Constants perform the same tasks as read-only variables with some differences. The differences between constants and read-only are

Constants:

1. Constants are dealt with at compile-time.2. Constants supports value-type variables.3. Constants should be used when it is very unlikely that the value will ever change.

Read-only:

1. Read-only variables are evaluated at runtime.2. Read-only variables can hold reference type variables.3. Read-only variables should be used when run-time calculation is required.

7. Differentiate between the while and for loop in C#.

The while and for loops are used to execute those units of code that need to be repeatedly

executed, unless the result of the specified condition evaluates to false. The only difference between the two is in their syntax. The for loop is distinguished by setting an explicit loop variable.

8. What is an identifier?

Identifiers are northing but names given to various entities uniquely identified in a program. The name of identifiers must differ in spelling or casing. For example, MyProg and myProg are two different

identifiers. Programming languages, such as C# and Visual Basic, strictly restrict the programmers from using any keyword as identifiers. Programmers cannot develop a class whose name is public, because, public is a keyword used to specify the accessibility of data in programs.

9. What does a break statement do in the switch statement?

The switch statement is a selection control statement that is used to handle multiple choices and transfer control to the case statements within its body. The following code snippet shows an example of the use of theswitch statement in C#: 

switch(choice)

Page 20: Interview Questions in ASP

{ case 1: console.WriteLine("First"); break; case 2: console.WriteLine("Second"); break; default: console.WriteLine("Wrong choice"); break;}

In switch statements, the break statement is used at the end of a case statement. The break statement is mandatory in C# and it avoids the fall through of one case statement to

another.

10. Explain keywords with example.

Keywords are those words that are reserved to be used for a specific task. These words cannot be used as identifiers. You cannot use a keyword to define the name of a variable or method. Keywords are used in programs to use the features of object-oriented programming. 

For example, the abstract keyword is used to implement abstraction and the inherits keyword is

used to implement inheritance by deriving subclasses in C# and Visual Basic, respectively. 

The new keyword is universally used in C# and Visual Basic to implement encapsulation by creating

objects.

11. Briefly explain the characteristics of value-type variables that are supported in the C# programming language.

The variables that are based on value types directly contain values. The characteristics of value-type variables that are supported in C# programming language are as follows:

All value-type variables derive implicitly from the System.ValueType class

You cannot derive any new type from a value type Value types have an implicit default constructor that initializes the default value of that type The value type consists of two main categories:

Structs - Summarizes small groups of related variables. Enumerations - Consists of a set of named constants.

12. Give the syntax of using the while loop in a C# program.

The syntax of using the while loop in C# is: 

Page 21: Interview Questions in ASP

while(condition) //condition{ //statements}

You can find an example of using the while loop in C#: 

int i = 0;while(i < 5){ Console.WriteLine("{0} ", i); i++;}

13. What is a parameter? Explain the new types of parameters introduced in C# 4.0.

A parameter is a special kind of variable, which is used in a function to provide a piece of information or input to a caller function. These inputs are called arguments. In C#, the different types of parameters are as follows:

Value type - Refers that you do not need to provide any keyword with a parameter. Reference type - Refers that you need to mention the ref keyword with a parameter. Output type - Refers that you need to mention the out keyword with a parameter.

Optional parameter - Refers to the new parameter introduced in C# 4.0. It allows you to neglect the parameters that have some predefined default values. The example of optional parameter is as follows:

public int Sum(int a, int b, int c = 0, int d = 0); /* c and d is optional */

Sum(10, 20); //10 + 20 + 0 + 0 Sum(10, 20, 30); //10 + 20 + 30 + 0 Sum(10, 20, 30, 40); //10 + 20 + 30 + 40

Named parameter - Refers to the new parameter introduced in C# 4.0. Now you can provide arguments by name rather than position. The example of the named parameter is as follows:

public void CreateAccount(string name, string address = "unknown", int age = 0);

CreateAccount("Sara", age: 30); CreateAccount(address: "India", name: "Sara");

14. Briefly explain the characteristics of reference-type variables that are supported in the C# programming language.

The variables that are based on reference types store references to the actual data. The keywords that are used to declare reference types are:

1. Class - Refers to the primary building block for the programs, which is used to encapsulate variables and methods into a single unit.

Page 22: Interview Questions in ASP

2. Interface - Contains only the signatures of methods, properties, events, or indexers.3. Delegate - Refers to a reference type that is used to encapsulate a named or anonymous

method.

15. What are the different types of literals?

A literal is a textual representation of a particular value of a type.

The different types of literals in Visual Basic are:

Boolean Literals - Refers to the True and False literals that map to the true and false state, respectively.

Integer Literals - Refers to literals that can be decimal (base 10), hexadecimal (base 16), or octal (base 8).

Floating-Point Literals - Refers to an integer literal followed by an optional decimal point By default, a floating-point literal is of type Double.

String Literals - Refers to a sequence of zero or more Unicode characters beginning and ending with an ASCII double-quote character.

Character Literals - Represents a single Unicode character of the Char type. Date Literals - Represents time expressed as a value of the Date type. Nothing - Refers to a literal that does not have a type and is convertible to all types in the type

system.

The different types of literals in C# are:

Boolean literals - Refers to the True and False literals that map to the true and false states, respectively.

Integer literals - Refers to literals that are used to write values of types int, uint, long, and ulong.

Real literals - Refers to literals that are used to write values of types float, double, and decimal. Character literals - Represents a single character that usually consists of a character in quotes,

such as 'a'. String literals - Refers to string literals, which can be of two types in C#:

A regular string literal consists of zero or more characters enclosed in double quotes, such as "hello".

A verbatim string literal consists of the @ character followed by a double-quote character, such as @"hello".

The Null literal - Represents the null-type.

16. What is the main difference between sub-procedure and function?

The sub-procedure is a block of multiple visual basic statements within Sub and End Sub statements. It is used to perform certain tasks, such as changing properties of objects, receiving or processing data, and displaying an output. You can define a sub-procedure anywhere in a program, such as in modules, structures, and classes.

Page 23: Interview Questions in ASP

We can also provide arguments in a sub-procedure; however, it does not return a new value.The function is also a set of statements within the Function and End Function statements. It is similar to sub-procedure and performs the same task. The main difference between a function and a sub-procedure is that sub-procedures do not return a value while functions do.

17. Determine the output of the code snippet.

int a = 29;a--;a -= ++a;Console.WriteLine("The value of a is: {0}", a);

/* The output of the code is -1. */

18. Differentiate between Boxing and Unboxing.

When a value type is converted to an object type, the process is known as boxing; whereas, when an object type is converted to a value type, the process is known as unboxing. 

Boxing and unboxing enable value types to be treated as objects. Boxing a value type packages it inside an instance of the Object reference type. This allows the value type to be stored on the garbage collected heap. Unboxing extracts the value type from the object. In this example, the integer variable i is boxed and assigned to object obj.

Example:

int i = 123;object obj = i; /* Thi line boxes i. */

/* The object obj can then be unboxed and assigned to integer variable i: */i = (int)obj; // unboxing

What is the significance of Finalize method in .NET?

.NET Garbage collector does almost all clean up activity for your objects. But unmanaged resources (example: Windows API created objects, File, Database connection objects, COM objects, etc.) are outside the scope of .NET Framework. We have to explicitly clean our resources. For these types of objects, .NET Framework provides Object.Finalize method, which can be overridden and clean up code for unmanaged resources can be put in this section?

Why is it preferred to not use finalize for clean up?

The problem with finalize is that garbage collection has to make two rounds in order to remove objects which have finalize methods.

Page 24: Interview Questions in ASP

The below figure will make things clear regarding the two rounds of garbage collection rounds performed for the objects having finalized methods.

Note: Few of the contents have been taken from various blogs/articles.In this scenario, there are three objects, Object1, Object2, and Object3. Object2 has the finalize method overridden and remaining objects do not have the finalize method overridden.Now when garbage collector runs for the first time, it searches for objects whose memory has to free. He can see three objects but only cleans the memory for Object1 and Object3. Object2it pushes to the finalization queue.Now garbage collector runs for the second time. He sees there are no objects to be released and then checks for the finalization queue and at this moment, it clears object2 from the memory. So if you notice, object2 was released from memory in the second round and not first. That is why the best practice is not to write clean up Non.NET resources in Finalize method rather use the DISPOSE.

What is the use of DISPOSE method?

Dispose method belongs to ‘IDisposable’ interface. We had seen in the previous section how bad it can be to override the finalize method for writing the cleaning of unmanaged resources. So if any object wants to release its unmanaged code, the best is to implementIDisposable and override the Dispose method of IDisposable interface. Now once your class has exposed the Dispose method, it is the responsibility of the client to call the Disposemethod to do the cleanup. How do I force the Dispose method to be called automatically, as clients can forget to call Dispose method?Call the Dispose method in Finalize method and in Dispose method, suppress thefinalize method using GC.SuppressFinalize. Below is the sample code of the pattern. This is the best way we do clean our unallocated resources and yes not to forget we do not get the hit of running the Garbage collector twice.

Page 25: Interview Questions in ASP

public class CleanClass : IDisposable { public void Dispose() { GC.SuppressFinalize(this); } protected override void Finalize() { Dispose(); } }

Note: Few of the content is taken from various blogs/articles.

What is an interface and what is an abstract class? Please expand by examples of using both. Explain why.

Answer 1In an interface class, all methods are abstract without implementation whereas in anabstract class, some methods we can define concrete. In interface, no accessibility modifiers are allowed. An abstract class may have accessibility modifiers. Interface and abstract class are basically a set of rules which you have to follow in case you are using them (inheriting them).

Answer 2Abstract classes are closely related to interfaces. They are classes that cannot be instantiated, and are frequently either partially implemented, or not at all implemented. One key difference between abstract classes and interfaces is that a class may implement an unlimited number of interfaces, but may inherit from only one abstract (or any other kind of) class. A class that is derived from an abstract class may still implement interfaces. Abstract classes are useful when creating components because they allow you to specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.

Answer 3

Abstract Classes

An abstract class is the one that is not used to create objects. An abstract class is designed to act as a base class (to be inherited by other classes). Abstract class is a design concept in program development and provides a base upon which other classes are built. Abstractclasses are similar to interfaces. After declaring an abstract class, it cannot be instantiated on its own, it must be inherited. Like interfaces, abstract classes can specify members that must be implemented in inheriting classes. Unlike interfaces, a class can inherit only one abstractclass. Abstract classes can only specify members that should be implemented by all inheriting classes.

Page 26: Interview Questions in ASP

Answer 4An interface looks like a class, but has no implementation. They’re great for putting together plug-n-play like architectures where components can be interchanged at will. Think Firefox Plug-in extension implementation. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks.

Answer 5One additional key difference between interfaces and abstract classes (possibly the most important one) is that multiple interfaces can be implemented by a class, but only one abstractclass can be inherited by any single class.

Some background on this: C++ supports multiple inheritance, but C# does not. Multiple inheritance in C++ has always be controversial, because the resolution of multiple inherited implementations of the same method from different base classes is hard to control and anticipate. C# decided to avoid this problem by allowing a class to implement multiple interfaces, which do not contain method implementations, but restricting a class to have at most a single parent class. Although this can result in redundant implementations of the same method when different classes implement the same interface, it is still an excellent compromise.

Another difference between interfaces and abstract classes is that an interface can be implemented by an abstract class, but no class, abstract or otherwise, can be inherited by an interface.

Answer 6

What is an Abstract class?

An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

What is an Interface?

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn’t support multiple inheritance, interfaces are used to implement multiple inheritance.

How does output caching work in ASP.NET?

Output caching is a powerful technique that increases request/response throughput by caching the content generated from dynamic pages. Output caching is enabled by

Page 27: Interview Questions in ASP

default, but output from any given response is not cached unless explicit action is taken to make the response cacheable.

To make a response eligible for output caching, it must have a valid expiration/validation policy and public cache visibility. This can be done using either the low-level OutputCache API or the high-level @ OutputCache directive. When output caching is enabled, an output cache entry is created on the first GET request to the page. Subsequent GET or HEAD requests are served from the output cache entry until the cached request expires.The output cache also supports variations of cached GET or POST name/value pairs.

The output cache respects the expiration and validation policies for pages. If a page is in the output cache and has been marked with an expiration policy that indicates that the page expires 60 minutes from the time it is cached, the page is removed from the output cache after 60 minutes. If another request is received after that time, the page code is executed and the page can be cached again. This type of expiration policy is called absolute expiration - a page is valid until a certain time.

What is connection pooling and how do you make your application use it?

Opening database connection is a time consuming operation.

Connection pooling increases the performance of the applications by reusing the active database connections instead of creating new connection for every request.

Connection pooling behaviour is controlled by the connection string parameters.

Following are the 4 parameters that control most of the connection pooling behaviour:

1. Connect Timeout2. Max Pool Size3. Min Pool Size4. Pooling

What are different methods of session maintenance in ASP.NET?

There are three types:

1. In-process storage2. Session State Service3. Microsoft SQL Server

In-Process Storage

The default location for session state storage is in the ASP.NET process itself.

Page 28: Interview Questions in ASP

Session State Service

As an alternative to using in-process storage for session state, ASP.NET provides the ASP.NET State Service. The State Service gives you an out-of-process alternative for storing session state that is not tied quite so closely to ASP. NET's own process.

To use the State Service, you need to edit the sessionState element in your ASP.NET application’s web.config file:You’ll also need to start the ASP.NET State Service on the computer that you specified in thestateConnectionString attribute. The .NET Framework installs this service, but by default it’s set to manual startup. If you’re going to depend on it for storing session state, you’ll want to change that to automatic startup by using the Services MMC plug-in in the Administrative Tools group.

If you make these changes, and then repeat the previous set of steps, you’ll see slightly different behavior: session state persists even if you recycle the ASP.NET process.

There are two main advantages to using the State Service. First, it is not running in the same process as ASP.NET, so a crash of ASP.NET will not destroy session information. Second, thestateConnectionString that’s used to locate the State Service includes the TCP/IP address of the service, which need not be running on the same computer as ASP.NET. This allows you to share state information across a web garden (multiple processors on the same computer) or even across a web farm (multiple servers running the application). With the default in-process storage, you can’t share state information between multiple instances of your application.

The major disadvantage of using the State Service is that it’s an external process, rather than part of ASP.NET. That means that reading and writing session state is slower than it would be if you kept the state in-process. And, of course, it’s one more process that you need to manage. As an example of the extra effort that this can entail, there is a bug in the initial release of the State Service that allows a determined attacker to crash the ASP.NET process remotely. If you’re using the State Service to store session state, you should install the patch from Microsoft Security Bulletin MS02-66, or install SP2 for the .NET Framework.

Microsoft SQL Server

The final choice for storing state information is to save it in a Microsoft SQL Server database. To use SQL Server for storing session state, you need to perform several setup steps:

Run the InstallSqlState.sql script on the Microsoft SQL Server where you intend to store session state. This script will create the necessary database and database objects. The .NET Framework installs this script in the same folder as its compilers and other tools–for example,C:\WINNT\Microsoft.NET\Framework\v1.0.3705 on a Windows 2000 computer with the 1.0 version of the Framework. Edit the sessionState element in the web.config file for your ASP.NET application as follows:Supply the server name, user name, and password for a SQL Server account that has access to the session state database in the sqlConnectionString attribute.

Page 29: Interview Questions in ASP

Like the State Service, SQL Server lets you share session state among the processors in a web garden or the servers in a web farm. But you also get the additional benefit of persistent storage. Even if the computer hosting SQL Server crashes and is restarted, the session state information will still be present in the database, and will be available as soon as the database is running again. That’s because SQL Server, being an industrial-strength database, is designed to log its operations and protect your data at (almost) all costs. If you’re willing to invest in SQL Server clustering, you can keep the session state data available transparently to ASP.NET even if the primary SQL Server computer crashes.

Like the State Service, SQL Server is slower than keeping session state in process. You also need to pay additional licensing fees to use SQL Server for session state in a production application. And, of course, you need to worry about SQL Server-specific threats such as the “Slammer” worm.

What does the "EnableViewState" property do? Why would I want it on or off?

Enable ViewState turns on the automatic state management feature that enables server controls to re-populate their values on a round trip without requiring you to write any code. This feature is not free however, since the state of a control is passed to and from the server in a hidden form field. You should be aware of when ViewState is helping you and when it is not. For example, if you are binding a control to data on every round trip (as in the datagridexample in tip #4), then you do not need the control to maintain its view state, since you will wipe out any re-populated data in any case. ViewState is enabled for all server controls by default. To disable it, set the EnableViewState property of the control to false.

What is the difference between Server.Transfer and Response.Redirect?

Why would I choose one over the other?

Server.Transfer(): client is shown as it is on the requesting page only, but all the content is of the requested page. Data can be persisted across the pages using Context.Item collection, which is one of the best ways to transfer data from one page to another keeping the page state alive.Response.Dedirect(): client know the physical location (page name and query string as well).Context.Items loses the persistence when navigating to destination page. In earlier versions of IIS, if we wanted to send a user to a new Web page, the only option we had wasResponse.Redirect. While this method does accomplish our goal, it has several important drawbacks. The biggest problem is that this method causes each page to be treated as a separate transaction. Besides making it difficult to maintain your transactional integrity,Response.Redirect introduces some additional headaches. First, it prevents good encapsulation of code. Second, you lose access to all of the properties in the Request object. Sure, there are workarounds, but they’re difficult. Finally, Response.Redirect necessitates a round trip to the client, which, on high-volume sites, causes scalability problems. As you might

Page 30: Interview Questions in ASP

suspect, Server.Transfer fixes all of these problems. It does this by performing the transfer on the server without requiring a roundtrip to the client.

Polymorphism, Method Hiding and Overriding

One of the fundamental concepts of object oriented software development is polymorphism. The term polymorphism (from the Greek meaning "having multiple forms") in OO is the characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow a variable to refer to more than one type of object.

Example Class Hierarchy

Let's assume the following simple class hierarchy with classes A, B and C for the discussions in this text. A is the super- or base class, B is derived from A and C is derived from class B. In some of the easier examples, we will only refer to a part of this class hierarchy.

Inherited Methods

A method Foo() which is declared in the base class A and not redeclared in classes B or C is inherited in the two subclasses:

using System; namespace Polymorphism { class A

Page 31: Interview Questions in ASP

{ public void Foo() { Console.WriteLine("A::Foo()"); } }

class B : A {}

class Test { static void Main(string[] args) { A a = new A(); a.Foo(); // output --> "A::Foo()"

B b = new B(); b.Foo(); // output --> "A::Foo()" } } }

The method Foo() can be overridden in classes B and C:

using System; namespace Polymorphism { class A { public void Foo() { Console.WriteLine("A::Foo()"); } }

class B : A { public void Foo() { Console.WriteLine("B::Foo()"); } }

class Test { static void Main(string[] args) { A a; B b;

a = new A(); b = new B(); a.Foo(); // output --> "A::Foo()" b.Foo(); // output --> "B::Foo()"

a = new B(); a.Foo(); // output --> "A::Foo()" } } }

There are two problems with this code.

The output is not really what we, say from Java, expected. The method Foo() is a non-virtual method. C# requires the use of the keyword virtual in order for a method to actually be virtual. An example using virtual methods and polymorphism will be given in the next section.

Page 32: Interview Questions in ASP

Although the code compiles and runs, the compiler produces a warning: ...\polymorphism.cs(11,15): warning CS0108: The keyword new is required on 'Polymorphism.B.Foo()' because it hides inherited member 'Polymorphism.A.Foo()'.

This issue will be discussed in section Hiding and Overriding Methods.

Note: Some of the content has been taken from various blogs/articles.

Virtual and Overridden Methods

Only if a method is declared virtual, derived classes can override this method if they are explicitly declared to override the virtual base class method with the override keyword.

using System; namespace Polymorphism { class A { public virtual void Foo() { Console.WriteLine("A::Foo()"); } }

class B : A { public override void Foo() { Console.WriteLine("B::Foo()"); } }

class Test { static void Main(string[] args) { A a; B b;

a = new A(); b = new B(); a.Foo(); // output --> "A::Foo()" b.Foo(); // output --> "B::Foo()"

a = new B(); a.Foo(); // output --> "B::Foo()" } } }

Method Hiding

Why did the compiler in the second listing generate a warning? Because C# not only supports method overriding, but also method hiding. Simply put, if a method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword. The correct class definition in the second listing is thus:

using System; namespace Polymorphism { class A

Page 33: Interview Questions in ASP

{ public void Foo() { Console.WriteLine("A::Foo()"); } }

class B : A { public new void Foo() { Console.WriteLine("B::Foo()"); } }

class Test { static void Main(string[] args) { A a; B b;

a = new A(); b = new B(); a.Foo(); // output --> "A::Foo()" b.Foo(); // output --> "B::Foo()"

a = new B(); a.Foo(); // output --> "A::Foo()" } } }

Combining Method Overriding and Hiding

Methods of a derived class can both be virtual and at the same time hide the derived method. In order to declare such a method, both keywords virtual and new have to be used in the method declaration:

class A { public void Foo() {} }

class B : A { public virtual new void Foo() {} }

A class C can now declare a method Foo() that either overrides or hides Foo() from class B:

class C : B { public override void Foo() {} // or public new void Foo() {} }

Note: Some of the content has been taken from various blogs/articles.

Page 34: Interview Questions in ASP

Conclusion C# is not Java. Only methods in base classes need not override or hide derived methods. All methods in

derived classes require to be either defined as new or as override. Know what you are doing and look out for compiler warnings.