Wednesday, April 27, 2011

Runtime polymorphism and compile time polymorphism

private void LogError(TextWriter tw, string msg)
{
tw.WriteLine(msg);
}

StreamWriter and StringWriter both derive from the abstract TextWriter base class. They both implement the WriteLine method. Depending on the type of the instance you pass into this method, it'll either write the message to a stream or to a string. LogMessage doesn't know or care which.

"With runtime polymorphism, the selection of a method for execution is based on the actual type of the object whose reference is stored in a reference variable, and not on the type of the reference variable on which the method is invoked."

23) Diffecernce between static class and sealed class

Sealed class..
The main purpose of a sealed class to take away the inheritance feature from the user so they cannot derive a class from a sealed class. One of the best usage of sealed classes is when you have a class with static members
Static class..
Static classes are used when a class provides functionality that is not specific to any unique instance. Here are the features of static classes in C# 2.0.

Static classes can not be instantiated.
Static classes are sealed so they can not be inherited.
Only static members are allowed.
Static classes can only have static constructor to initialize static members.

How to prevent class from being instantiated.

1) Make the class an abstract base class.

abstract class Person {
}
class Programmer : Person {
}
var person = new Person(); // compile time error
var programmer = new Programmer(); // ok
2) Create private constructor to class
class test
{
    // Private Constructor:
    private test{ }
    public static double e = System.Math.E;  //2.71828...
}

3) Static class

Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.

The main features of a static class are:

· They only contain static members.

· They cannot be instantiated.

· They are sealed.

Creating a static class is therefore much the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.

The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.

Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state

Constant_ReadOnly_Static keyword

Constants

  • Constants are static by default
  • They must have a value at compilation-time (you can have e.g. 3.14 * 2, but cannot call methods)
  • Could be declared within functions
  • Are copied into every assembly that uses them (every assembly gets a local copy of values)
  • Can be used in attributes

Readonly instance fields

  • Must have set value by the time constructor exits
  • Are evaluated when instance is created

Static readonly fields

  • Are evaluated when code execution hits class reference (when new instance is created or a static method is executed)
  • Must have an evaluated value by the time the static constructor is done
  • It's not recommended to put ThreadStaticAttribute on these (static constructors will be executed in one thread only and will set the value for its thread; all other threads will have this value uninitialized)

Keywords in C#

Sealed

Virtual

Override

Abstract

Base

New

“this” for extention method

Private constructor

Static

:

Base()

Void

Access Modifier

Private: If we define a variable in a class as private, then we cannot use that variable further more in any different class.


Public: If we define a variable in a class as public, then we can use that variable further more in any class.

Protected: If we use a protected access modifier for a variable or method, then they can be accessible by their inherited classes only.

Internal: If we declare a variable as internal, then we can use this variable with in the library. This access modifier can only be used for library functions.

Protected internal: This is same as protected but the only difference is, it is useful only in libraries.

MasterPage_ContentPage_WebControL Sequence

Scenario 1:

Master page - Content page

Sequence of events

Content Page PreInit Event

Master Page Init Event

Content Page Init Event

Content Page Load Event

Master Page Load Event

If we are using master page and want to changes theme or decide which master page need to be load at runtime then we need to use Content page PreInit event.

Scenario 2:

Master page - Content page - Web user control on master page only.

Content Page PreInit Event

Master: UserControl Init Event

Master Page Init Event

Content Page Init Event

Content Page Load Event

Master Page Load Event

Master: UserControl Load Event

Scenario 3:

Master page - web user control on master page - Content page - Web user control on master page only.

Content Page PreInit Event

Content Page UserControl Init Event

Master:UserControl Init Event

Master Page Init Event

Content Page Init Event

Content Page Load Event

Master Page Load Event

Page:UserControl Load Event

Master:UserControl Load Event

PreRender - Page
PreRender - MasterPage
PreRender - UserControl

Unload - ChildUserControl
Unload - UserControl
Unload - MasterPage
Unload - Page

Conclusion :

1) PreInit for Content Page is first event

2) Init event sequence: UsercontrolàMaster PageàContent Page

3) Load event sequence: Content Page àMaster Pageà Usercontrol

4) Prerender event sequence is same as Load

5) Unload is exact reverse of load. Same as Init

UsercontrolàMaster PageàContent Page

6) Init and unload are same sequence

7) Load and prerender has same sequence

8) Webcontrol on content page has precedence over usercontrol in master page

ASP.NET Interview Question

Question 1. Explain the differences between Server-side and Client-side code?
Answer Server side code will execute at server (where the website is hosted) end, & all the business logic will execute at server end where as client side code will execute at client side (usually written in javascript, vbscript, jscript) at browser end.

Question 2. What type of code (server or client) is found in a Code-Behind class?
Answer Server side code.

Question 3. How to make sure that value is entered in an asp:Textbox control?
Answer Use a RequiredFieldValidator control.

Question 4. Which property of a validation control is used to associate it with a server control on that page?
Answer ControlToValidate property.

Question 5. How would you implement inheritance using VB.NET & C#?
Answer C# Derived Class : Baseclass
VB.NEt : Derived Class Inherits Baseclass

Question 6. Which method is invoked on the DataAdapter control to load the generated dataset with data?
Answer Fill() method.

Question 7. What method is used to explicitly kill a user's session?
Answer Session.Abandon()

Question 8. What property within the asp:gridview control is changed to bind columns manually?
Answer Autogenerated columns is set to false

Question 9. Which method is used to redirect the user to another page without performing a round trip to the client?
Answer Server.Transfer method.

Question 10. How do we use different versions of private assemblies in same application without re-build?
AnswerInside the Assemblyinfo.cs or Assemblyinfo.vb file, we need to specify assembly version.
assembly: AssemblyVersion

Question 11. Is it possible to debug java-script in .NET IDE? If yes, how?
Answer Yes, simply write "debugger" statement at the point where the breakpoint needs to be set within the javascript code and also enable javascript debugging in the browser property settings.

Question 12. How many ways can we maintain the state of a page?
Answer 1. Client Side - Query string, hidden variables, viewstate, cookies
2. Server side - application , cache, context, session, database

Question 13. What is the use of a multicast delegate?
Answer A multicast delegate may be used to call more than one method.

Question 14. What is the use of a private constructor?
Answer A private constructor may be used to prevent the creation of an instance for a class.

Question 15. What is the use of Singleton pattern?
Answer A Singleton pattern .is used to make sure that only one instance of a class exists.

Question 16. When do we use a DOM parser and when do we use a SAX parser?
Answer The DOM Approach is useful for small documents in which the program needs to process a large portion of the document whereas the SAX approach is useful for large documents in which the program only needs to process a small portion of the document.

Question 17. Will the finally block be executed if an exception has not occurred?
AnswerYes it will execute.

Question 18. What is a Dataset?
Answer A dataset is an in memory database kindof object that can hold database information in a disconnected environment.

Question 19. Is XML a case-sensitive markup language?
Answer Yes.

Question 20. What is an .ashx file?
Answer It is a web handler file that produces output to be consumed by an xml consumer client (rather than a browser).
Question 21. What is encapsulation?
Answer Encapsulation is the OOPs concept of binding the attributes and behaviors in a class, hiding the implementation of the class and exposing the functionality.

Question 22. What is Overloading?
Answer When we add a new method with the same name in a same/derived class but with different number/types of parameters, the concept is called overluoad and this ultimately implements Polymorphism.

Question 23. What is Overriding?
Answer When we need to provide different implementation in a child class than the one provided by base class, we define the same method with same signatures in the child class and this is called overriding.

Question 24. What is a Delegate?
Answer A delegate is a strongly typed function pointer object that encapsulates a reference to a method, and so the function that needs to be invoked may be called at runtime.

Question 25. Is String a Reference Type or Value Type in .NET?
Answer String is a Reference Type object.

Question 26. What is a Satellite Assembly?
Answer Satellite assemblies contain resource files corresponding to a locale (Culture + Language) and these assemblies are used in deploying an application globally for different languages.

Question 27. What are the different types of assemblies and what is their use?
Answer Private, Public(also called shared) and Satellite Assemblies.

Question 28. Are MSIL and CIL the same thing?
Answer Yes, CIL is the new name for MSIL.

Question 29. What is the base class of all web forms?
Answer System.Web.UI.Page

Question 30. How to add a client side event to a server control?
Answer Example... BtnSubmit.Attributes.Add("onclick","javascript:fnSomeFunctionInJavascript()");

Question 31. How to register a client side script from code-behind?
Answer Use the Page.RegisterClientScriptBlock method in the server side code to register the script that may be built using a StringBuilder.

Question 32. Can a single .NET DLL contain multiple classes?
Answer Yes, a single .NET DLL may contain any number of classes within it.

Question 33. What is DLL Hell?
Answer DLL Hell is the name given to the problem of old unmanaged DLL's due to which there was a possibility of version conflict among the DLLs.

Question 34. can we put a break statement in a finally block?
Answer The finally block cannot have the break, continue, return and goto statements.

Question 35. What is a CompositeControl in .NET?
Answer CompositeControl is an abstract class in .NET that is inherited by those web controls that contain child controls within them.

Question 36. Which control in asp.net is used to display data from an xml file and then displayed using XSLT?
Answer Use the asp:Xml control and set its DocumentSource property for associating an xml file, and set its TransformSource property to set the xml control's xsl file for the XSLT transformation.

Question 37. Can we run ASP.NET 1.1 application and ASP.NET 2.0 application on the same computer?
Answer Yes, though changes in the IIS in the properties for the site have to be made during deployment of each.

Question 38. What are the new features in .NET 2.0?
Answer Plenty of new controls, Generics, anonymous methods, partial classes, iterators, property visibility (separate visibility for get and set) and static classes.

Question 39. Can we pop a MessageBox in a web application?
Answer Yes, though this is done clientside using an alert, prompt or confirm or by opening a new web page that looks like a messagebox.

Question 40. What is managed data?
Answer The data for which the memory management is taken care by .Net runtime’s garbage collector, and this includes tasks for allocation de-allocation.
Question 41. How to instruct the garbage collector to collect unreferenced data?
Answer We may call the garbage collector to collect unreferenced data by executing the System.GC.Collect() method.

Question 42. How can we set the Focus on a control in ASP.NET?
Answer txtBox123.Focus(); OR Page.SetFocus(NameOfControl);

Question 43. What are Partial Classes in Asp.Net 2.0?
Answer In .NET 2.0, a class definition may be split into multiple physical files but partial classes do not make any difference to the compiler as during compile time, the compiler groups all the partial classes and treats them as a single class.

Question 44. How to set the default button on a Web Form?
Answer

Question 45.Can we force the garbage collector to run?
Answer Yes, using the System.GC.Collect(), the garbage collector is forced to run in case required to do so.

Question 46. What is Boxing and Unboxing?
Answer Boxing is the process where any value type can be implicitly converted to a reference type object while Unboxing is the opposite of boxing process where the reference type is converted to a value type.

Question 47. What is Code Access security? What is CAS in .NET?
Answer CAS is the feature of the .NET security model that determines whether an application or a piece of code is permitted to run and decide the resources it can use while running.

Question 48. What is Multi-tasking?
Answer It is a feature of operating systems through which multiple programs may run on the operating system at the same time, just like a scenario where a Notepad, a Calculator and the Control Panel are open at the same time.

Question 49. What is Multi-threading?
Answer When an application performs different tasks at the same time, the application is said to exhibit multithreading as several threads of a process are running.2

Question 50. What is a Thread?
Answer A thread is an activity started by a process and its the basic unit to which an operating system allocates processor resources.

Question 51. What does AddressOf in VB.NET operator do?
Answer The AddressOf operator is used in VB.NET to create a delegate object to a method in order to point to it.

Question 52. How to refer to the current thread of a method in .NET?
Answer In order to refer to the current thread in .NET, the Thread.CurrentThread method can be used. It is a public static property.

Question 53. How to pause the execution of a thread in .NET?
Answer The thread execution can be paused by invoking the Thread.Sleep(IntegerValue) method where IntegerValue is an integer that determines the milliseconds time frame for which the thread in context has to sleep.

Question 54. How can we force a thread to sleep for an infinite period?
Answer Call the Thread.Interupt() method.

Question 55. What is Suspend and Resume in .NET Threading?
Answer Just like a song may be paused and played using a music player, a thread may be paused using Thread.Suspend method and may be started again using the Thread.Resume method. Note that sleep method immediately forces the thread to sleep whereas the suspend method waits for the thread to be in a persistable position before pausing its activity.

Question 56. How can we prevent a deadlock in .Net threading?
Answer Using methods like Monitoring, Interlocked classes, Wait handles, Event raising from between threads, using the ThreadState property.

Question 57. What is Ajax?
Answer Asyncronous Javascript and XML - Ajax is a combination of client side technologies that sets up asynchronous communication between the user interface and the web server so that partial page rendering occur instead of complete page postbacks.

Question 58. What is XmlHttpRequest in Ajax?
Answer It is an object in Javascript that allows the browser to communicate to a web server asynchronously without making a postback.

Question 59. What are the different modes of storing an ASP.NET session?
Answer InProc (the session state is stored in the memory space of the Aspnet_wp.exe process but the session information is lost when IIS reboots), StateServer (the Session state is serialized and stored in a separate process call Viewstate is an object in .NET that automatically persists control setting values across the multiple requests for the same page and it is internally maintained as a hidden field on the web page though its hashed for security reasons.

Question 60. What is a delegate in .NET?
Answer A delegate in .NET is a class that can have a reference to a method, and this class has a signature that can refer only those methods that have a signature which complies with the class.
Question 61. Is a delegate a type-safe functions pointer?
Answer Yes

Question 62. What is the return type of an event in .NET?
Answer There is No return type of an event in .NET.

Question 63. Is it possible to specify an access specifier to an event in .NET?
Answer Yes, though they are public by default.

Question 64. Is it possible to create a shared event in .NET?
Answer Yes, but shared events may only be raised by shared methods.

Question 65. How to prevent overriding of a class in .NET?
Answer Use the keyword NotOverridable in VB.NET and sealed in C#.

Question 66. How to prevent inheritance of a class in .NET?
Answer Use the keyword NotInheritable in VB.NET and sealed in C#.

Question 67. What is the purpose of the MustInherit keyword in VB.NET?
Answer MustInherit keyword in VB.NET is used to create an abstract class.

Question 68. What is the access modifier of a member function of in an Interface created in .NET?
Answer It is always public, we cant use any other modifier other than the public modifier for the member functions of an Interface.

Question 69. What does the virtual keyword in C# mean?
Answer The virtual keyword signifies that the method and property may be overridden.

Question 70. How to create a new unique ID for a control?
Answer ControlName.ID = "ControlName" + Guid.NewGuid().ToString(); //Make use of the Guid class

Question 71A. What is a HashTable in .NET?
Answer A Hashtable is an object that implements the IDictionary interface, and can be used to store key value pairs. The key may be used as the index to access the values for that index.

Question 71B. What is an ArrayList in .NET?
Answer Arraylist object is used to store a list of values in the form of a list, such that the size of the arraylist can be increased and decreased dynamically, and moreover, it may hold items of different types. Items in an arraylist may be accessed using an index.

Question 72. What is the value of the first item in an Enum? 0 or 1?
Answer 0

Question 73. Can we achieve operator overloading in VB.NET?
Answer Yes, it is supported in the .NET 2.0 version, the "operator" keyword is used.

Question 74. What is the use of Finalize method in .NET?
Answer .NET Garbage collector performs all the clean up activity of the managed objects, and so the finalize method is usually used to free up the unmanaged objects like File objects, Windows API objects, Database connection objects, COM objects etc.

Question 75. How do you save all the data in a dataset in .NET?
Answer Use the AcceptChanges method which commits all the changes made to the dataset since last time Acceptchanges was performed.

Question 76. Is there a way to suppress the finalize process inside the garbage collector forcibly in .NET?
Answer Use the GC.SuppressFinalize() method.

Question 77. What is the use of the dispose() method in .NET?
Answer The Dispose method in .NET belongs to IDisposable interface and it is best used to release unmanaged objects like File objects, Windows API objects, Database connection objects, COM objects etc from the memory. Its performance is better than the finalize() method.

Question 78. Is it possible to have have different access modifiers on the get and set methods of a property in .NET?
Answer No we can not have different modifiers of a common property, which means that if the access modifier of a property's get method is protected, and it must be protected for the set method as well.

Question 79. In .NET, is it possible for two catch blocks to be executed in one go?
Answer This is NOT possible because once the correct catch block is executed then the code flow goes to the finally block.

Question 80. Is there any difference between System.String and System.StringBuilder classes?
Answer System.String is immutable by nature whereas System.StringBuilder can have a mutable string in which plenty of processes may be performed.
Question 81. What technique is used to figure out that the page request is a postback?
Answer The IsPostBack property of the page object may be used to check whether the page request is a postback or not. IsPostBack property is of the type Boolean.

Question 82. Which event of the ASP.NET page life cycle completely loads all the controls on the web page?
Answer The Page_load event of the ASP.NET page life cycle assures that all controls are completely loaded. Even though the controls are also accessible in Page_Init event but here, the viewstate is incomplete.

Question 83. How is ViewState information persisted across postbacks in an ASP.NET webpage?
Answer Using HTML Hidden Fields, ASP.NET creates a hidden field with an ID="__VIEWSTATE" and the value of the page's viewstate is encoded (hashed) for security.

Question 84. What is the ValidationSummary control in ASP.NET used for?
Answer The ValidationSummary control in ASP.NET displays summary of all the current validation errors.

Question 85. What is AutoPostBack feature in ASP.NET?
Answer In case it is required for a server side control to postback when any of its event is triggered, then the AutoPostBack property of this control is set to true.

Question 86. What is the difference between Web.config and Machine.Config in .NET?
Answer Web.config file is used to make the settings to a web application, whereas Machine.config file is used to make settings to all ASP.NET applications on a server(the server machine).

Question 87. What is the difference between a session object and an application object?
Answer A session object can persist information between HTTP requests for a particular user, whereas an application object can be used globally for all the users.

Question 88. Which control has a faster performance, Repeater or Datalist?
Answer Repeater.

Question 89. Which control has a faster performance, Datagrid or Datalist?
Answer Datalist.

Question 90. How to we add customized columns in a Gridview in ASP.NET?
Answer Make use of the TemplateField column.

Question 91. Is it possible to stop the clientside validation of an entire page?
Answer Set Page.Validate = false;

Question 92. Is it possible to disable client side script in validators?
Answer Yes. simply EnableClientScript = false.

Question 93. How do we enable tracing in .NET applications?
Answer <%@ Page Trace="true" %>

Question 94. How to kill a user session in ASP.NET?
Answer Use the Session.abandon() method.

Question 95. Is it possible to perform forms authentication with cookies disabled on a browser?
Answer Yes, it is possible.

Question 96. What are the steps to use a checkbox in a gridview?
Answer



Question 97. What are design patterns in .NET?
Answer A Design pattern is a repeatitive solution to a repeatitive problem in the design of a software architecture.

Question 98. What is difference between dataset and datareader in ADO.NET?
Answer A DataReader provides a forward-only and read-only access to data, while the DataSet object can carry more than one table and at the same time hold the relationships between the tables. Also note that a DataReader is used in a connected architecture whereas a Dataset is used in a disconnected architecture.

Question 99. Can connection strings be stored in web.config?
Answer Yes, in fact this is the best place to store the connection string information.

Question 100. Whats the difference between web.config and app.config?
Answer Web.config is used for web based asp.net applications whereas app.config is used for windows based applications.