cast to ref object

K

Kimmo Laine

Hi,

how can i cast to ref object, in C#:

internal void Foo( ref object o ) {
// . . .
}

// . . .

MyClass1 mc1 = new MyClass1();
MyClass2 mc2 = new MyClass2();

Foo( ( ??? )mc1 );
Foo( ( ??? )mc2 );


thx

Kimmo Laine
 
J

Jon Skeet [C# MVP]

Kimmo Laine said:
how can i cast to ref object, in C#:

internal void Foo( ref object o ) {
// . . .
}

// . . .

MyClass1 mc1 = new MyClass1();
MyClass2 mc2 = new MyClass2();

Foo( ( ??? )mc1 );
Foo( ( ??? )mc2 );

You can't. Imagine if the implementation of Foo did:

void Foo (ref object o)
{
o = new object();
}

What would you expect to happen then?

Pass-by-reference parameters must match type exactly. The workaround is
to do:

object o = mc1;
Foo (ref o);
mc1 = (MyClass1) o;
 
M

Morten Wennevik

Hi Kimmo,

Why do you want to cast it to object?

Foo(ref mc1);

should work just fine as it derives from object

Foo(ref (object)mc1);

should work too, but is unecessary.
 
J

Jon Skeet [C# MVP]

Morten Wennevik said:
Why do you want to cast it to object?

Foo(ref mc1);

should work just fine as it derives from object

Foo(ref (object)mc1);

should work too, but is unecessary.

No, neither work.

From the spec:

<quote>
When a formal parameter is a reference parameter, the corresponding
argument in a method invocation must consist of the keyword ref
followed by a variable-reference (§12.3.3) of the same type as the
formal parameter
</quote>

Compare that with:

<quote>
When a formal parameter is a value parameter, the corresponding
argument in a method invocation must be an expression of a type that is
implicitly convertible (§13.1) to the formal parameter type.
</quote>
 

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

Similar Threads


Top