Passing subclass as parameter

  • Thread starter Thread starter ToChina
  • Start date Start date
T

ToChina

Hi, I have the following code:

class A
{
}

class B : A
{
}

and a method of another class which is like so:

void MethodName(ref A blah)
{
blah.Whatever = 0;
}

I'm calling the method with the subclass B:

B subclass = new B();
MethodName(ref subclass);

However, I'm getting the compiler error:

The best overloaded method match for 'MethodName(ref A)' has some invalid
arguments
error CS1503: Argument '1': cannot convert from 'ref B' to 'ref A'

What am I missing? :P
 
ToChina,

You need to cast the instance of B down to A. If you have class C which
derives from A, and MethodName changes subclass to be an instance of C, then
you could not assign it to the variable containing the instance of B. So,
to fix this, you would do this:

// Create an instance of B
B subclass = new B();

// Cast down to A
A param = subclass;

// Make the call.
MethodName(ref param);

You have to be careful when you are done with param though, as you can't
guarantee that it will be an instance of type B (well, you could be, if you
write the code).

Hope this helps.
 
ToChina said:
class A
{
}

class B : A
{
}

and a method of another class which is like so:

void MethodName(ref A blah)
{
blah.Whatever = 0;
}

I'm calling the method with the subclass B:

B subclass = new B();
MethodName(ref subclass);

However, I'm getting the compiler error:

The best overloaded method match for 'MethodName(ref A)' has some invalid
arguments
error CS1503: Argument '1': cannot convert from 'ref B' to 'ref A'

What am I missing? :P

Parameters which are passed by reference need to be *exactly* the same
type. Imagine if the code in MethodName said:

blah = new A();

then by the time the method returned, the "subclass" variable's value
would no longer be a reference to an instance of the subclass!

My guess, however, is that you're passing by reference when you really
don't have to. You certainly don't have to in the example above.

See http://www.pobox.com/~skeet/csharp/parameters.html for more
information.
 
Back
Top