Shadowing Question

N

Nick Stansbury

Hi,

Quick (and probably simple) question regarding shadowing and
polymorphism. Problem is best explained by an example.

Public Class A
public CommonProperty as Integer
end class

Public Class AB : Inherits A
Public Specific as String
End Class

Public Class AC : Inherits A
Public Exclusive as Boolean
End Class

Public ClassB
Public MemberObject as new A
End Class

Public Class BA : Inherits B
Public shadows MemberObject as new AB
End Class

Question:

If I treat an instance of class BA as an instance of Class B and then
assign MyInstance.MemberObject to an instance of AB which I have downcast to
an instance of A what happens? Does the compiler figure everything out and
raise errors if I try to upcast a polymorphed AC (as an A) to
BA.MemberObject ?

Thanks!

Nick
 
S

Scott Allen

Hi Nick:

The important concept to realize with the Shadows keyword is that a
new field will result in the class. If you assign to the field through
a base class reference you are actually assigning to the shadowed
field.

In other words:

Dim myBA As New BA
Dim myB As B

myB = CType(myBA, B)

myB.MemberObject = New AC

Console.WriteLine(myB.MemberObject.CommonProperty)
If myBA.MemberObject Is Nothing Then
Console.WriteLine("myBA.MemberObject is Nothing")
End If

Will spit out:

0
myBA.MemberObject is Nothing

We've assigned to the field B::A, leaving BA::A uninitialized.
Making sense?
 
N

Nick Stansbury

Thanks - that was basically what I'd feared. It's a limitation that you
can't override a function where the only difference is the return type - and
that makes the functionality I've described here impossible without getting
messy. Any ideas on how to do this?
Nick
 
S

Scott Allen

Hi Nick:

The approach in the Framework is to basically embed the return type
into the method for simple types. For instance, SqlDataReader has a
set of GetXXX(index) methods where you pass the index of a column and
it returns the value. GetBoolean, GetByte, GetInt32.
 

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

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top