分享
 
 
 

Boxing and UnBoxing in C#

王朝c#·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

source:

http://www.codeproject.com/csharp/BoxUnBox.asp

begin:

Introduction

In this article I will explain the concepts of Boxing and UnBoxing. C# provides us with Value types and Reference Types. Value Types are stored on the stack and Reference types are stored on the heap. The conversion of value type to reference type is known as boxing and converting reference type back to the value type is known as unboxing.

Let me explain you little more about Value and Reference Types.

Value Types

Value types are primitive types that are mapped directly to the FCL. Like Int32 maps to System.Int32, double maps to System.double. All value types are stored on stack and all the value types are derived from System.ValueType. All structures and enumerated types that are derived from System.ValueType are created on stack, hence known as ValueType.

Reference Types

Reference Types are different from value types in such a way that memory is allocated to them from the heap. All the classes are of reference type. C# new operator returns the memory address of the object.

Examples

Lets see some examples to have a better understanding of Value Types and Reference Types. Since we know that all ValueTypes are derived from System.Value we can write something like this:

System.ValueType r = 5;

So what do you think about the above line of code. Will it compile ? Yes it will compile. But wait what type is it cause I don't remember any type which is called System.ValueType since its a base class from which all value types inherit. So is it Int32, Int64,double, decimal etc. It turns out that the type for variable 'r' is System.Int32. The Question arrises why Int32 and why not Int16. Well its because it is mapped to Int32 by default depending upon the Initial value of the variable.

You cannot write something like this since System.ValueType is not a primitive type its a base class for primitive value types and these mathematical operations can be performed on primitive types.

System.ValueType r = 10;

r++;

In the above example I told you that variable 'r' will be a System.Int32 variable but if you don't believe me than you can find out yourself using the GetType() method:

System.ValueType r = 5;

Console.WriteLine(r.GetType()) // returns System.Int32;

Here are few samples you can try on your own:

System.ValueType r = 23.45;

Console.WriteLine(r.GetType()); // what does this print

//-------------------------------------------------------

System.ValueType r = 23.45F;

Console.WriteLine(r.GetType()); // What does this print

//-------------------------------------------------------

System.ValueType r = 2U;

Console.WriteLine(r.GetType()); // What does this print

//-------------------------------------------------------

System.ValueType r = 'c';

Console.WriteLine(r.GetType()); // What does this print

//-------------------------------------------------------

System.ValueType r = 'ac';

Console.WriteLine(r.GetType()); // tricky

//-------------------------------------------------------

System.ValueType r = "Hello World";

Console.WriteLine(r.GetType()); // tricky

Lets now jump to Boxing. Sometimes we need to convert ValueTypes to Reference Types also known as boxing. Lets see a small example below. You see in the example I wrote "implicit boxing" which means you don't need to tell the compiler that you are boxing Int32 to object because it takes care of this itself although you can always make explicit boxing as seen below right after implicit boxing.

Int32 x = 10;

object o = x ; // Implicit boxing

Console.WriteLine("The Object o = {0}",o); // prints out 10

//-----------------------------------------------------------

Int32 x = 10;

object o = (object) x; // Explicit Boxing

Console.WriteLine("The object o = {0}",o); // prints out 10

Lets now see UnBoxing an object type back to value type. Here is a simple code that unbox an object back to Int32 variable. First we need to box it so that we can unbox.

Int32 x = 5;

object o = x; // Implicit Boxing

x = o; // Implicit UnBoxing

So, you see how easy it is to box and how easy it is to unbox. The above example first boxs Int32 variable to an object type and than simply unbox it to x again. All the conversions are taking place implicitly. Everything seems right in this example there is just one small problem which is that the above code is will not compile. You cannot Implicitly convert a reference type to a value type. You must explicity specify that you are unboxing as shown in the code below.

Int32 x = 5;

object o = x; // Implicit Boxing

x = (Int32)o; // Explicit UnBoxing

Lets see another small example of unboxing.

Int32 x = 5; // declaring Int32

Int64 y = 0; // declaring Int64 double

object o = x; // Implicit Boxing

y = (Int64)o; // Explicit boxing to double

Console.WriteLine("y={0}",y);

This example will not work. It will compile successfully but at runtime It will generate an exception of System.InvalidCastException. The reason is variable x is boxed as Int32 variable so it must be unboxed to Int32 variable. So, the type the variable uses to box will remain the same when unboxing the same variable. Of course you can cast it to Int64 after unboxing it as Int32 as follows:

Int32 x = 5; // declaring Int32

Int64 y = 0; // declaring Int64 double

object o = x; // Implicit Boxing

y = (Int64)(Int32)o; // Unboxing and than casting to double

Console.WriteLine("y={0}",y);

I am sure that you all have grasp the basic understanding of Boxing and Unboxing. Happy Coding and practise a lot !

About azamsharp

About Mohammad Azam

Mohammad Azam is currently a Computer Science undergraduate student at University of Houston. He has been using .NET Technologies exclusively for past couple of years. He is also the author of several Asp.net and C# articles which have been published on official website of Microsoft.

Mohammad Azam is also ranked as top 100 poster on Asp.net forums hosted by Microsoft.

For consulting services please email at iamazam@hotmail.com or visit the website at

http://www.azamsharp.cjb.net

Click here to view azamsharp's online profile.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有