I get a compiler error below. I donβt know why I cannot take a reference to a derived class and pass it to a method that accepts a reference to the base class. Note that the foo () and bar () methods do not necessarily have the same semantics, so they must have different names, these methods are not a problem.
public class X { public int _x; } public class Y : X { public int _y; } public class A { public void foo( ref X x ) { x._x = 1; } } public class B : A { public void bar( ref Y y ) { foo( ref y ); // generates compiler error foo( ref (X)y); // wont work either y._y = 2; } }
The only solution I found was:
public class B : A { public void bar( ref Y y ) { X x = y; foo( ref x ); // works y._y = 2; } }
I know that "y" is never initialized in bar (), but since its declared as ref itself must be initialized outside the method, so the problem cannot be the problem. Any coverage that you can shed on this question would be helpful. I am sure that this is just my understanding of C #, which is not enough, it will work in C ++ with the cast.
c #
Timo
source share