Click to See Complete Forum and Search --> : Getting a base class new instance


druven
May 22nd, 2005, 07:09 AM
Hello all,

Suppose I have class B which inherits class A:

Class A
{
dim x as integer
}

Class B
inherits A
{
dim y as integer
}

I have an instance of class B, and I want to get from it an instance of class A with same property values. For example:

dim b as new B
b.x = 1
b.y = 2
dim a as A
a = b.GET_BASE_CLASS_IN_SOME_WAY
messagebox.show(a.x) //will show '1' in messagebox
messagebox.show(a.y) //error - prohibited

What can I do in the fifth line of code to get a reference to a ??
Help will be fully appreciated, thanks

coolbiz
May 22nd, 2005, 07:21 PM
Dim bObj As new B
bObj.X = 1
bObj.Y = 2

Dim aObj As A = CType(bObj, A)
or
Dim aObj As A = DirectCast(bObj, A)

druven
May 23rd, 2005, 02:50 AM
It looks fine but a function I call that expects object of type A fail with the argument CType(b, A).

When I look in debug Watch window I see that the type of the new instance I get from CType is actualy B.

How can I make it work ?

coolbiz
May 23rd, 2005, 05:59 AM
If your function expects type A, then you don't even have to do the conversion. You can pass in bObj directly into that function the FW will take care of the conversion.

What exactly is the error message that you get?