Casting question


S

schoenfeld1

Is there a way to cast an object type to a ref struct type?

For example, I need to call the method

public SomeMethod(ref SomeStruct s);

and I need to pass an object o as the parameter. How can I cast o to
(ref SomeStruct s)?




-- here is what I need it for ----

protected override void WndProc(ref Message m) {
if (Asynchronous) {
ManagedThreadPool.QueueUserWorkItem(
new WaitCallback(AsyncWndProc), m);
} else {
AsyncWndProc(m);
}
}


private void AsyncWndProc(object o) {
if (o is Message) { // how do i check if o is a (ref Message)?
base.WndProc(o as Message); // how do cast o to (ref Message)?
}
}
 
Ad

Advertisements

D

Daniel O'Connell [C# MVP]

Is there a way to cast an object type to a ref struct type?

For example, I need to call the method

public SomeMethod(ref SomeStruct s);

and I need to pass an object o as the parameter. How can I cast o to
(ref SomeStruct s)?

You can't. Ref only affects parameters.

In yoru case what you want is
if (o is Message)
{
Message s = (Message)o;
base.WndProc(ref s);
}
 
G

Guest

How can I cast o to (ref SomeStruct s)?

"ref" is not part of the type - it is only a parameter passing thing - so
you cannot cast to "ref", nor do you need to.
if (o is Message) { // how do i check if o is a (ref Message)?

That should do it, ref is not part of the type, so o is just a Message.
base.WndProc(o as Message); // how do cast o to (ref Message)?

I did not compile your example, but I think this should work:

Message m = (Message)o; // use cast syntax, not as operator to unbox
base.WndProc(ref m);
 
S

schoenfeld1

Daniel said:
You can't. Ref only affects parameters.

In yoru case what you want is
if (o is Message)
{
Message s = (Message)o;
base.WndProc(ref s);
}

Okay thanks all for your tips. I forgot that boxing/unboxing was
automatic in .net

So "Message s = (Message)o" will actually copy sizeof(Message) bytes
from 'o' into the runtime stack for parameter 's'?

 
Ad

Advertisements

G

Guest

So "Message s = (Message)o" will actually copy sizeof(Message) bytes
from 'o' into the runtime stack for parameter 's'?

Essentially, yes.

If Message is a value type and s is a local variable or parameter, then its
memory will come from the stack.

The assignment will copy the value (you can think of it as a bitwise or
shallow copy).
 

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