Wednesday, 5 January 2011

Boxing and Unboxing

Hi there,

Check this out:

Say you have a page that perform simple calculation like below:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="BoxingUnBoxing.aspx.cs" Inherits="BoxingUnBoxing" %>

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Boxing Unboxingtitle>

head>

<body>

<form id="form1" runat="server">

<div>

<asp:TextBox ID="txtValue1" runat="server">asp:TextBox>

+

<asp:TextBox ID="txtValue2" runat="server">asp:TextBox>

=

<asp:TextBox ID="txtValue3" runat="server">asp:TextBox> <asp:Button ID="btnAdd"

runat="server" OnClick="btnAdd_Click" Text="Button" />div>

form>

body>

html>

On your code behind you have function to perform calculation

protected void btnAdd_Click(object sender, EventArgs e)

{

int value1 = Convert.ToInt32(txtValue1.Text); // unboxing, convert reference type to value type

int value2 = Convert.ToInt32(txtValue2.Text); // unboxing, convert reference type to value type

int value3 = value1 + value2; // calculate here

txtValue3.Text = Convert.ToString(value3); // boxing, convert value type back to reference type

}