Boxing and Unboxing in TypeScript
Boxing and Unboxing is an essential concept in TypeScript. TypeScript automatically transforms a value type into a reference type; this automatic transformation is called Boxing. In other words, the conversion of a value type to a reference type is known as Boxing and reference type to value type is known as Unboxing.
Here, I am describing Boxing and Unboxing separately.
Boxing
Conversion of value type to reference type (Object):
- var x: number=100;
- var obj: Object=x;
Unboxing
Conversion of reference type to value type:
- var a: number=100;
- var obj: Object=x;
- var y: number=parseInt(obj.toString());
The following example tells you, how to use Boxing and Unboxing in TypeScript. Use the following to create a program using Boxing and Unboxing
.
Step 1
Open Visual Studio 2012 and click on "File" menu -> "New" -> "Project". A window will be opened; provide the name of your application, like "BoxingAndUnBoxing", then click on the Ok button.
Step 2
After Step 1 your project has been created. The Solution Explorer, which is at the right side of Visual Studio, contains the js file, ts file, CSS file, and HTML files.
Step 3
The code of the Boxing and Unboxing
program:
BoxingAndUnBoxing.ts
- class BoxingAndUnBoxing {
- MyFunction() {
- var a: number = 100;
- var b: number;
- var obj: Object;
- obj = a;
- b = parseInt(obj.toString());
- alert("Boxing value=" + obj + " Unboxing value=" + a);
- }
- }
- window.onload = () => {
- var data = new BoxingAndUnBoxing();
- data.MyFunction();
- }
Note In the above-declared program a and b are number type variables and obj is an object type (reference type). When you assign a value of a to obj, it automatically (implicitly) transforms the value type to a reference type, and whenever you want to do the reverse process, then the object value must be typecast because TypeScript does not convert an object type (reference type) to a value type implicitly.
default.html
- <!DOCTYPEhtml>
- <htmllang="en"
- xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <metacharset="utf-8"/>
- <title>TypeScript HTML App</title>
- <linkrel="stylesheet"href="app.css"type="text/css"/>
- <scriptsrc="app.js">
- </script>
- </head>
- <body>
- <h1>TypeScript Boxing and Unboxing</h1>
- <divid="content"/>
- </body>
- </html>
app.js
- var BoxingAndUnBoxing = (function() {
- function BoxingAndUnBoxing() {}
- BoxingAndUnBoxing.prototype.MyFunction = function() {
- var a = 100;
- var b;
- var obj;
- obj = a;
- b = parseInt(obj.toString());
- alert("Boxing value" + obj + " Unboxing value" + a);
- };
- return BoxingAndUnBoxing;
- })();
- window.onload = function() {
- var data = new BoxingAndUnBoxing();
- data.MyFunction();
- };