473,378 Members | 1,407 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

unboxing : Please tell me the difference

Hi all
I am a bit confuse about unboxing... what is the difference and what
is best practice ?

object o = __box(1234);

int n = *dynamic_cast<__box int*>(o);

of

int n = Convert::ToInt32(o);

thanks in advance
Nov 17 '05 #1
5 1736
Hello !

The first approach is correct, in terms of language specification. The
Convert class is used to convert .NET basic types between each other. The
..NET basic types are Boolean, Char, SByte, Byte, Int16, Int32, Int64,
UInt16, UInt32, UInt64, Single, Double, Decimal, DateTime and String.

Boxing and unboxing are terms used to - as documentation states -
"conversion between managed objects and value types". In english, the most
common use is to convert from C++ base types 'int, char, float, double, long
etc' to .NET basic types and back again. The easiest way to think of this is
remembering that C++ basic types and .NET basic types are two different
worlds. To convert from C++ basic type into a .NET basic type, you use
boxing. To convert back, you use unboxing.

Also, boxing and unboxing are used when converting from __value classes to
managed objects and back again. Remember that unless otherwise specified,
Managed C++ creates the .NET basic types as value types. Thus, even these
types can be converted to objects and vice versa. However, when dealing with
..NET, you should always attempt to create it's types and objects into the
managed heap, and leave the unmanaged stack and heap for unmanaged types.
Mixing these two is a sure way to summon trouble your way.

So, "the correct way" to do this is:

object o = __box( (int)1234 );

int n = *dynamic_cast<__box int*>(o);

-Antti Keskinen
"chenedor" <fi******@hotmail.com> wrote in message
news:78**************************@posting.google.c om...
Hi all
I am a bit confuse about unboxing... what is the difference and what
is best practice ?

object o = __box(1234);

int n = *dynamic_cast<__box int*>(o);

of

int n = Convert::ToInt32(o);

thanks in advance

Nov 17 '05 #2
Antti Keskinen wrote:
Hello !

The first approach is correct, in terms of language specification. The
Convert class is used to convert .NET basic types between each other. The
.NET basic types are Boolean, Char, SByte, Byte, Int16, Int32, Int64,
UInt16, UInt32, UInt64, Single, Double, Decimal, DateTime and String.

Boxing and unboxing are terms used to - as documentation states -
"conversion between managed objects and value types". In english, the most
common use is to convert from C++ base types 'int, char, float, double, long
etc' to .NET basic types and back again. The easiest way to think of this is
remembering that C++ basic types and .NET basic types are two different
worlds. To convert from C++ basic type into a .NET basic type, you use
boxing. To convert back, you use unboxing.

Also, boxing and unboxing are used when converting from __value classes to
managed objects and back again. Remember that unless otherwise specified,
Managed C++ creates the .NET basic types as value types. Thus, even these
types can be converted to objects and vice versa. However, when dealing with
.NET, you should always attempt to create it's types and objects into the
managed heap, and leave the unmanaged stack and heap for unmanaged types.
Mixing these two is a sure way to summon trouble your way.

So, "the correct way" to do this is:

object o = __box( (int)1234 );

Object *o, and the cast inside __box is not needed.
int n = *dynamic_cast<__box int*>(o);

Apart from being mentioned in an MS book, what is the reason of using
dynamic_cast here and not static_cast?

What I consider as the correct way:
#using <mscorlib.dll>

int main()
{
using namespace System;

Object *o = __box(1234);

int n = *static_cast<__box int*>(o);
}

--
Ioannis Vranos
Nov 17 '05 #3
>
int n = *dynamic_cast<__box int*>(o);

Apart from being mentioned in an MS book, what is the reason of using
dynamic_cast here and not static_cast?

What I consider as the correct way:

int main()
{
using namespace System;

Object *o = __box(1234);

int n = *static_cast<__box int*>(o);
}


Hi,

It was my belief (though this is coming from a mainly native C++ background)
that static_cast was generally frowned upon (mainly because of the lack of
type-safety)... is this not considered the case in managed C++? In any case,
apart from the (certainly in this case) insignificant performance hit, what
would be the advantage one way or the other? Certainly in the past I've only
ever used static_cast in conversions between numeric types (e.g. ints to
floats) and although in this case you're pretty sure 'o' is a boxed int,
that might not necessarily be the case in a slightly more complex example.

Steve
Nov 17 '05 #4
Steve McLellan wrote:
int main()
{
using namespace System;

Object *o = __box(1234);

int n = *static_cast<__box int*>(o);
}

Hi,

It was my belief (though this is coming from a mainly native C++ background)
that static_cast was generally frowned upon (mainly because of the lack of
type-safety)... is this not considered the case in managed C++? In any case,
apart from the (certainly in this case) insignificant performance hit, what
would be the advantage one way or the other? Certainly in the past I've only
ever used static_cast in conversions between numeric types (e.g. ints to
floats) and although in this case you're pretty sure 'o' is a boxed int,
that might not necessarily be the case in a slightly more complex example.

Check this for a quick overview of casts:

http://groups.google.com/groups?hl=e....gr%26rnum%3D4
If the above does not work, try this:

http://groups.google.com/groups?selm...&output=gplain

dynamic_cast is for RTTI (Run-time type identification) and its return
value should be checked before use. It is used in cases like:

void somefunc(void *p)
{

SomeClass *r= dynamic_cast<SomeClass *>(p);

// p is a SomeClass
if(r!=0)
// ...

// ...
}
and so on.

static_cast on the other hand are compile-time checked (that they are
related) conversions between types in the same hierarchy.
So static_cast makes sense here.


--
Ioannis Vranos
Nov 17 '05 #5
chenedor wrote:
Hi all
I am a bit confuse about unboxing... what is the difference and what
is best practice ?

object o = __box(1234);

int n = *dynamic_cast<__box int*>(o);


A couple of comments. First, the above may exhibit undefined behavior or
cause a NullReferenceException. If the dynamic_cast fails, it returns a
null pointer, which the code above de-references anyway. If you're going to
use dynamic_cast, it only makes sense if you write something like:

__box int* pi = dynamic_cast<__box int*>(o);

if (pi)
n = *pi;

Second, under the CLR all casts are dynamic as is the un-boxing operation.
Here's a simple example to illustrate the differences under the covers:

#using <mscorlib.dll>

#pragma managed

void f()
{
System::Object* o = __box(1234);
int n = *dynamic_cast<__box int*>(o);
int m = *static_cast<__box int*>(o);
}

Compile this with cl -clr -c -FAsc and look at the .COD file that's
produced:

; 6 : {

0000c 14 ldnull 0 ; i32 0x0
0000d 0a stloc.0 ; _o$

; 7 : System::Object* o = __box(1234);

0000e 20 d2 04 00 00 ldc.i4 1234 ; i32 0x4d2
00013 8c 00 00 00 00 box ?<clref>@Int32@System@@2HA
00018 0a stloc.0 ; _o$

; 8 :
; 9 : int n = *dynamic_cast<__box int*>(o);

00019 06 ldloc.0 ; _o$
0001a 75 00 00 00 00 isInst ?<clref>@Int32@System@@2HA
0001f 79 00 00 00 00 unbox ?<clref>@Int32@System@@2HA
00024 4a ldind.i4
00025 0c stloc.2 ; _n$

; 10 :
; 11 : int m = *static_cast<__box int*>(o);

00026 06 ldloc.0 ; _o$
00027 79 00 00 00 00 unbox ?<clref>@Int32@System@@2HA
0002c 4a ldind.i4
0002d 0b stloc.1 ; _m$
$L1344:

; 12 : }

Note that the unbox operation is identical in both cases, and that both
cases pass the expected type (System::Int32) to the unbox operation. The
only difference is that dynamic_cast inserted an isInst instruction, the
result of which was ignored.

So, there is reason to use dynamic_cast if you're not sure the cast will
succeed, but in those cases be sure to test the result of the cast before
using it, otherwise you're just turning a bad cast exception into a numm
reference exception. When you "know" that the cast will succeed, use
static_cast. The same rules apply in native C++ programming, except that
de-referencing a null pointer is undefined behavior instead of a guaranteed
NullReferenceException.

-cd
Nov 17 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Andy Read | last post by:
Dear all, From the following examples. Can anyone please tell me why the C# IL produces the unbox statement and the VB doesn't? * Forgive me if the code isn't perfect, I don't have VS.NET on...
43
by: Mountain Bikn' Guy | last post by:
I have a situation where an app writes data of various types (primitives and objects) into a single dimensional array of objects. (This array eventually becomes a row in a data table, but that's...
2
by: emma middlebrook | last post by:
Hi Is this class and code snippet not good enough to see the differences between having a collection of a value type compared with having a collection of references to a reference type...
24
by: ALI-R | last post by:
Hi All, First of all I think this is gonna be one of those threads :-) since I have bunch of questions which make this very controversial:-0) Ok,Let's see: I was reading an article that When...
6
by: David Young | last post by:
I'm using hashtables to transport data between layers in my app, but in so doing, it seems almost impossible to avoid unboxing. private static BusinessObject PackageBusinessObject(Hashtable...
13
by: gökhan | last post by:
Hi! I fear this question might be too basic, however being a c++ veteran I have trouble to get a good desing in c# running. // a base class class Vector{}; // inherited class class...
19
by: ahjiang | last post by:
hi there,, what is the real advantage of boxing and unboxing operations in csharp? tried looking ard the internet but couldnt find any articles on it. appreciate any help
161
by: Peter Olcott | last post by:
According to Troelsen in "C# and the .NET Platform" "Boxing can be formally defined as the process of explicitly converting a value type into a corresponding reference type." I think that my...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.