Boxing m.m

T

Tony Johansson

Hello!

I have three questions.
1. When is it useful to use boxing for value types.
2. I have earlier been using C and C++ for many years but the last year I
have been using C#.
In C# you can use pointer if you use unsafe directive but I can't see any
purpose to use the unsafe directive
with pointer. Is it right that the use of unsafe code with pointer is of no
use?
3.When you use the unboxing is it always nessesary that the type in the box
is always the same as the cast type.
An example
int i = 23;
object o = i;
i = (int)o;


//Tony
 
B

Ben Voigt [C++ MVP]

Tony Johansson said:
Hello!

I have three questions.
1. When is it useful to use boxing for value types.

Pretty much never, now that we have type-safe generic collections.
2. I have earlier been using C and C++ for many years but the last year I
have been using C#.
In C# you can use pointer if you use unsafe directive but I can't see any
purpose to use the unsafe directive
with pointer. Is it right that the use of unsafe code with pointer is of
no use?

No, but it is never necessary. You may get better performance with
pointers, then unsafe code would be useful.
3.When you use the unboxing is it always nessesary that the type in the
box is always the same as the cast type.
An example
int i = 23;
object o = i;
i = (int)o;

That's right, you must first unbox by casting to the original type, then you
can convert.

int i = 23;
object o = i;
short s = (short)(int)o; // ok
s = (short)o; // runtime error
 
J

Jon Skeet [C# MVP]

That's right, you must first unbox by casting to the original
type, then you can convert.

Note that there are a few oddities around this in reality, which are
due to the semantics of the CLR. I can't remember many off the top of
my head, other than enums:

using System;

class Test
{
enum Fred : int
{
Foo,
Bar
}

static void Main()
{
Fred x = Fred.Bar;
object o = x;
int i = (int)o; // This works

Console.WriteLine(i);
}
}

But yes, it's a good idea to always unbox to the original type - that
should *always* work :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top