Thursday, December 16, 2010

Value Type, Reference type & Boxing & Unboxing

 While drawing my one notes I gone through many contrasting views about where reference & value type are stored so i delved further by searching through many experts comment ,I collected following information most of it is from MSDN as it is authentic source for such information.I Wish the dust be settle down so that programmer can get better idea of it.

a) Value Types: The value types consist of two main categories namely Structs & Enumerations. Structs fall into these categories Numeric types, bool & User defined structs. Numeric types can be again of three types Integral types, Floating-point types &decimal types
Main Features of Value Types: Variable that are based on value types directly contains a values. Assigning one value type variable to another copies the contained value. This differs from the assignment of reference type variables, which copies a reference to the object but not the object itself. All value types are derived implicitly from the System.ValueType.
    Unlike reference types, it is not possible to derive a new type from a value type. However, like reference types, structs can implement interfaces.
   Unlike reference types, it is not possible for a value type to contain the null value. However, the nullable types feature does allow values types to be assigned to null.
   Each value type has an implicit default constructor that initializes the default value of that type.
Value types are implicitly derived from system.ValueType, which in turn derived from System.Object. Deriving from system.ValueType is not allowed. Even individual   value types like int are sealed.
Primitive types: The primitive types are identified through keywords.
      E.g. int k;
     Keywords are aliases for predefined types in the System namespace. In our Example above ‘int’ is an alias for system.int32. So instance of int i.e. ‘k’ can be treated as instances of system.int32.
      Constant expressions, whose operands are all primitive types constants, are evaluated at                compilation time.
      Primitive types can be initialized using literals. For example, 'A' is a literal of the type    char and 2001 is a literal of the type int.
Initializing Value Types
Local variables in C# must be initialized before being used. Therefore, if you declare a local variable without initialization like this:
int myInt;
you cannot use it before you initialize it. You can initialize it using the following statement:
myInt = new int();  // Invoke default constructor for int type.

which is equivalent to:
myInt = 0;
You can, of course, have the declaration and the initialization in the same statement like this:
int myInt = new int();
int myInt = 0;

Using the new operator calls the default constructor of the specific type and assigns the default value to the variable. In the preceding example, the default constructor assigned the value 0 to myInt.

With user-defined types, use new to invoke the default constructor.
 For example, the following statement invokes the default constructor of the Point struct:
Point p = new Point (); // Invoke default constructor for the struct.
After this call, the struct is considered to be definitely assigned; that is, all of its members are initialized to their default values.

All Value types are derived from System.ValueType, which in turn derived from system.Object.Point to note that one can’ t derived from System.ValueType. Value types do not take null value.
A variable that is of type value directly contains a value. Assigning a variable of type value to another variable of type value COPIES that value.

b) Reference Type:

Reference types inherit directly from System.Object. Reference types are stored on the managed heap, thus they are under the control of Garbage Collector.
Two or more reference type variables can refer to a single object in the heap, allowing operations on one variable to affect the object referenced by the other variable. The variable representing the instance contains a pointer to the instance of the class
c) Value Type vs. Reference Type:
  • A variable that is of type value directly contains a value. Assigning a variable of type value to another variable of type value COPIES that value.
  • A variable of type reference, points to a place in memory where the actual object is contained. Assigning a variable of type reference to another variable of type reference copies that reference (it tells the new object where the place in memory is), but does not make a copy of the object.
  • Value types are stored on the stack.
  • Reference types are stored on the heap.
  • Value types can not contain the value null. *
  • Reference types can contain the value null.
  • Value types have a default implied constructor that initializes the default value.
  • Reference types default to a null reference in memory.

  • Value types derive from System.ValueType.
  • Reference types derive from System.Object.

  • Value types cannot derive a new type from an existing value type, but they are able to implement interfaces.
  • Reference types can derive a new type from an existing reference type as well as being able to implement interfaces.
  • Changing the value of one value type does not affect the value of another value type.
  • Changing the value of one reference type MAY change the value of another reference type.
  • The nullable type (only in .NET 2.0) can be assigned the value null.
c) Boxing: Boxing is a process of converting a value type into a reference type. Boxing is used to store value types in the garbage-collected heap. It is an implicit conversion of a Value Types to the type object or to any interface type implemented by this value type.
Boxing a value type allocates an object instance on the heap and copies the value into the new object.
Boxing Conversion
It also possible to perform the boxing explicitly but seldom needed.
int i = 123;
object o = (object)i;  // explicit boxing

This example converts an integer variable i to an object o by means of boxing. Then, the value stored in the variable i is changed from 123 to 456. The example shows that the original value type and the boxed object use separate memory locations, and therefore can store different values.
class TestBoxing
    static void Main()
        int i = 123;
        object o = i;  // implicit boxing
        i = 456;  // change the contents of i
        System.Console.WriteLine("The value-type value = {0}", i);
        System.Console.WriteLine("The object-type value = {0}", o);


The value-type value = 456
The object-type value = 123
d) Unboxing: Unboxing is process of converting a reference type to value type. It extracts the value type from the object.
Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface.
 An unboxing operation consists of:
·         Checking the object instance to make sure it is a boxed value of the given value type.
·         Copying the value from the instance into the value-type variable.
The following statements demonstrate both boxing and unboxing operations:
int i = 123;      // a value type
object o = i;     // boxing
int j = (int)o;  // unboxing

The following figure demonstrates the result of the preceding statements.
Unboxing Conversion
For the unboxing of value types to succeed at run time, the item being unboxed must be a reference to an object that was previously created by boxing an instance of that value type. Attempting to unbox null or a reference to an incompatible value type will result in an InvalidCastException.
The following example demonstrates a case of invalid unboxing and the resulting InvalidCastException. Using try and catch, an error message is displayed when the error occurs.
class TestUnboxing
    static void Main()
        int i = 123;
        object o = i;  // implicit boxing
            int j = (short)o;  // attempt to unbox
            System.Console.WriteLine("Unboxing OK.");
        catch (System.InvalidCastException e)
            System.Console.WriteLine("{0} Error: Incorrect unboxing.", e.Message);


Specified cast is not valid. Error: Incorrect unboxing.
If you change the statement:
int j = (short) o;
int j = (int) o;
the conversion will be performed, and you will get the output:
Unboxing OK.


In relation to simple assignments, boxing and unboxing are computationally expensive processes. When a value type is boxed, an entirely new object must be allocated and constructed. To a lesser degree, the cast required for unboxing is also expensive computationally.

Wednesday, December 15, 2010

ASP.NET Page Life Cycle

      When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps. It is important to understand the page life cycle so that we will able to write code at the appropriate life-cycle stage for the effect we intended to be.
The page goes through the stages outlined in the following table. Some parts of the life cycle occur only when a page is processed as a postback. Page life cycle is the same during a partial-page postback as it is during a full-page postback.

Page request
The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.
In the start stage, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. The page also sets the UICulture property.
During page initialization, controls on the page are available and each control's UniqueID property is set. A master page and themes are also applied to the page if applicable. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.
During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.
Postback event handling
If the request is a postback, control event handlers are called. After that, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.
Before rendering, view state is saved for the page and all controls. During the rendering stage, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream object of the page's Response property.
The Unload event is raised after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and cleanup is performed.

Life-Cycle Events

      Within each stage of the life cycle of a page, the page raises events that one can handle to run his own code. Pages also support automatic event wire-up, meaning that ASP.NET looks for methods with particular names and automatically runs those methods when certain events are raised. If the AutoEventWireup attribute of the @ Page directive is set to true, page events are automatically bound to methods that use the naming convention of Page_event, such as Page_Load and Page_Init.

The following table lists the page life-cycle events that are used most frequently. There are more events than those listed; however, they are not used for most page-processing scenarios. Instead, they are primarily used by server controls on the ASP.NET Web page to initialize and render themselves.
Page Event Typical Use
PreInit Raised after the start stage is complete and before the initialization stage begins.
Init Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page.
InitComplete Raised at the end of the page's initialization stage. Only one operation takes place between the Init and InitComplete events: tracking of view state changes is turned on. View state tracking enables controls to persist any values that are programmatically added to the ViewState collection. Until view state tracking is turned on, any values added to view state are lost across postbacks. Controls typically turn on view state tracking immediately after they raise their Init event.
PreLoad Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance.
Load The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page.
Control events Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.
LoadComplete Raised at the end of the event-handling stage.
PreRender Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls. (To do this, the Page object calls EnsureChildControls for each control and for the page.)
PreRenderComplete Raised after each data bound control whose DataSourceID property is set calls its DataBind method. For more information, see Data Binding Events for Data-Bound Controls later in this topic.
SaveStateComplete Raised after view state and control state have been saved for the page and for all controls. Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.
Render This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control's markup to send to the browser.
Unload Raised for each control and then for the page.

Bellow is list that is more elaborate:
PreInit :The master page and content page are merged during the initialization stage of page processing so master page must be assigned before it that is why one can change master page dynamically only at PreInit event.
     This is the only event where programmatic access to master pages and themes is allowed. This event is not recursive, meaning that it is accessible only for the page itself and not for any of its child controls.
Init: The “Init” event is fired reclusively for the page itself and for all the child controls in the hierarchy. The “Init” event is fired first for the most bottom control in the hierarchy, and then fired up the hierarchy until it is fired for the page itself. The initialization event can be overridden using the OnInit method. At this event the Viewstate tracking is not yet enabled.
                You can call the “Page. TrackViewState ()” method at the start of the “Init” event and thus enabling tracking. In this case, the “Init” event will behave exactly like the “InitComplete” event, to be discussed next.

InitComplete: signals the end of the initialization phase. It is at the start of this event that tracking of the ASP.NET Viewstate is turned on by using TrackViewState() method of control      e.g. Page. TrackViewState ()
LoadViewState: Occurs only at postback. This is a recursive event first it fires for control at bottom of hierarchy then for page itself.Here, the Viewstate which has been saved in the __VIEWSTATE during the previous page visit (via the SaveViewState event) is loaded and then populated into the control hierarchy.


LoadPostbackdata: Occurs only at postback. This is a recursive event first it fires for control at bottom of hierarchy then for page itself. During this event, the posted form data is loaded into the appropriate controls. This is why when one post a form, he find that the posted data is loaded again into the appropriate controls.

   Viewstate is not responsible for preserving posted data.Try to disable the Viewstate on a TextBox control or even on the entire page, and you will find that the posted data is still preserved. It is due to the virtue of the LoadPostbackdata event.
PreLoad: The PreLoad event is raised after all postback data processing and before the Load event. There is a second attempt to load postback data before the OnLoadComplete event.
Load: This is a recursive event first it fires for control at bottom of hierarchy then for page itself. All objects are first arranged in the page DOM (called the Control Tree in ASP.NET) .Here, You can access view state information and Web form POST data from this event. You can also access other server controls within the page's control hierarchy.
The Load event can be overridden by calling OnLoad

Control events (RaisePostbackEvent): Occurs only at postback. What this event does is inspect all child controls of the page and determine if they need to fire any postback events. If it finds such controls, then these controls fire their events.

   If the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.

LoadComplete: Use this event for tasks that require that all other controls on the page be loaded.
Prerender: This is a recursive event first it fires for page at top of hierarchy then for control down the hierarchy. Use the event to make final changes to the contents of the page or its controls before the rendering stage begins. Any changes in the view state of the server control can be saved during this event. Such changes made in the rendering phase will not be saved.
PreRenderComplete: This is the last event raised before the page's view state is saved. The right place to put in the last logic before ViewState is saved.

SaveViewstate: This is a recursive event like Init. During this event, the Viewstate of the page is constructed and serialized into the __VIEWSTATE hidden field.

SaveStateControl: In 2.0 the Control State is used to store the UI state of a control such as the sorting and paging of a DataGrid. The Control State is also serialized and stored in the same __VIEWSTATE hidden field. The Control State cannot be set off.
SaveStateComplete: Raised after view state and control state have been saved for the page and for all controls.  Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.

Render: This is a recursive called method on page and it’s control like Init. The Render method takes an HtmlTextWriter object as a parameter and uses that to output HTML to be streamed to the browser.

Changes can still be made at this point, but they are reflected to the client only. Can be used to move Viewstate hidden field downward for SEO purpose.

Unload: This is a recursive event first it fires for control at bottom of hierarchy then for page itself. Use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.

   You should destroy any objects or references you have created in building the page. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object.