Simple: Class casting question?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello

Thank for reviewing this question. I would like to know why I am getting a syntax error. For example

public class



public class B : public



Init(ref A




B b=new B()
Init(ref b); // compiler erro
Init(b); // leave off both "ref" and it compiles fine


if I have a function that takes a reference to class A, why can't I pass in a reference to class B since it is derived from class A. If I leave off the "ref", it works, but I want a reference instead

Many Thank
Pete
 
Peter said:
public class A
{
}

public class B : public A
{
}

Init(ref A)
{
}

{
B b=new B();
Init(ref b); // compiler error
Init(b); // leave off both "ref" and it compiles fine.
}

if I have a function that takes a reference to class A, why can't I pass in a reference to class B since it is derived from class A. If I leave off the "ref", it works, but I want a reference instead.

Hi Peter,

there is no need to use the "ref". As class A and B are implicitly
derived from System.Object they are reference-types and they will be
passed as references without using ref.

Cheers

Arne Janning
 
Peter said:
Thank for reviewing this question. I would like to know why I am
getting a syntax error. For example,

public class A
{
}

public class B : public A
{
}

Init(ref A)
{
}

{
B b=new B();
Init(ref b); // compiler error
Init(b); // leave off both "ref" and it compiles fine.
}

if I have a function that takes a reference to class A, why can't I
pass in a reference to class B since it is derived from class A.

You can, and indeed you already *are* passing a reference to a class B
instance, as B is a reference type.
If I leave off the "ref", it works, but I want a reference instead.

You already have *a* reference. You're just not passing *by* reference.
The reason you can't pass b *by* reference is that the implementation
of Init could be:

a = new A();

(assuming you provided a name of a for the parameter to Init).

which would mean that after the method call, b was no longer a
reference to an instance of B.

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